Upload
phan-trong-chi
View
19
Download
0
Embed Size (px)
DESCRIPTION
Java_Threads
Citation preview
Chapter 6Threads in Java
1
Java Simplified / Session 22 / 2 of 45
Multitasking vs MultiThreading Define a thread Define multithreading List benefits of multithreading Create threads Discuss thread states Manage threads Explain how to set thread priorities Describe a daemon thread
Objectives
2
Java Simplified / Session 22 / 3 of 45
Multitasking: là khả năng của một OS cho phép chạy nhiều chương trình đồng thời
trên một CPU (đơn nhân) Thực hiện bằng cách phân bổ thời gian chuyển hoạt động từ một
chương này sang chương trình khác (ms). Process
Khi chạy 1 ứng dụng (program) OS sẽ cấp phát riêng cho nó bộ nhớ và các tài nguyên khác -> 1 process.
Các bộ nhớ và các tài nguyên của 1 process chỉ nó mới được phép truy nhập
Thread: Một process có thể có một hoặc nhiều tác vụ khác nhau và có thể chạy
đồng thời. 1 tác vụ là 1 Thread: 1 dòng điều khiển trong phạm vi một tiến trình
Một số khái niệm
3
Java Simplified / Session 22 / 4 of 45
Thread là đơn vị nhỏ nhất trong mã chương trình có thể thực thi một công việc riêng biệt.
Thread hình thành gồm: một định danh luồng (thread ID), một bộ đếm chương trình, tập thanh ghi và ngăn xếp.
Nó chia sẻ với các Thread khác thuộc cùng một tiến trình phần mã, phần dữ liệu, và tài nguyên hệ điều hành như các tập tin đang mở và các tín hiệu.
Thread
4
Java Simplified / Session 22 / 5 of 45
Truyền thống: Một tiến trình có một thread điều khiển đơn. Hoạt động của Single Thread:
Chỉ có một tuyến đoạn đang chạy tại một thời điểm cho trước. Các tuyến đoạn khác phải chờ:
Hệ điều hành duy trì một hàng đợi các tuyến đoạn và phân bổ thời gian CPU cho chúng
Gây lãng phí CPU và bộ nhớ Hiện đại: Một tiến trình có nhiều luồng điều khiển,
nó có thể thực hiện nhiều hơn một tác vụ tại một thời điểm.
Khi đó, các tuyến đoạn có thể truy xuất tới tài nguyên dùng chung để cùng làm việc hợp tác với nhau => MultiThreads
Thread & MultiThread
5
Java Simplified / Session 22 / 6 of 456
Single vs. Multi-Threaded
Java Simplified / Session 22 / 7 of 457
Single vs. Multi-Threaded • A process that is made of one thread is known as
single-threaded process.
• A process that creates two or more threads is
called a multithreaded process. For example, any Web browser, such as Internet Explorer is a multithreaded application.
Step 1 Step 2 … Step n
Step 1 Step 2 … Step n
Step 1 Step 2 … Step n
Java Simplified / Session 22 / 8 of 45
Applications of threads
Web Browser: Thread hiện thị hình ảnh, Thread hiện thị văn bản; Thread lấy dữ liệu từ mạng…
MS Word: Thread hiện thị đồ họa; Thread đọc sự nhấn phím của NSD; Thread kiểm tra chính tả…
8
Java Simplified / Session 22 / 9 of 45
Luồng cũng đóng một vai trò quan trọng trong hệ thống lời gọi thủ tục xa (RPC).
Khi một trình phục vụ nhận một thông điệp, nó phục vụ thông điệp dùng một luồng riêng. Điều này cho phép phục vụ nhiều yêu cầu đồng hành.
Ứng dụng mạng trong lập trình mạng
Applications of threads
9
Java Simplified / Session 22 / 10 of 45
Sự đáp ứng: MultiThread một ứng dụng giao tiếp cho phép một
chương trình tiếp tục chạy thậm chí nếu một phần của nó bị khóa (wait) hay đang thực hiện một thao tác dài,
do đó gia tăng sự đáp ứng đối với người dùng.. Chia sẻ tài nguyên:
Mặc định, các Thread chia sẻ bộ nhớ và các tài nguyên của các quá trình mà chúng thuộc về.
Thuận lợi của việc chia sẻ là nó cho phép một ứng dụng có nhiều hoạt động của các Thread khác nhau nằm trong cùng không gian địa chỉ.
Benefits of Multithreading
10
Java Simplified / Session 22 / 11 of 45
Kinh tế: cấp phát bộ nhớ và các tài nguyên cho việc tạo các quá
trình là rất đắt (chậm). Vì các Thread chia sẻ tài nguyên của quá trình mà chúng
thuộc về nên nó kinh tế hơn việc tạo quá trình và chuyển ngữ cảnh giữa các Thread .
Sử dụng kiến trúc đa xử lý: các lợi điểm của MultiThread có thể phát huy trong kiến
trúc đa xử lý, ở đó mỗi Thread thực thi song song trên một bộ xử lý khác nhau.
Một quá trình đơn Thread chỉ có thể chạy trên một CPU. MultiThread trên một máy nhiều CPU gia tăng tính đồng hành.
Benefits of Multithreading
11
Java Simplified / Session 22 / 12 of 45
Multithreading requires less overhead than multitasking. In multitasking, các chương trình chạy trên các
không gian địa chỉ của chúng và khác nhau giữa các chương trìnhđòi hỏi nhiều tài nguyên của hệ thống (cả ram và CPU)
In multithreading các tác vụ có thể chia sẻ cùng không gian địa chỉ
Multithreading cho phép viết các chương trình có hiệu quả cao với sự tận dụng CPU là tối đa bằng cách duy trì thời gian trễ là tối thiểu.
Multithreading vs. multitasking
12
Java Simplified / Session 22 / 13 of 45
Luồng nhân: Được hỗ trợ trực tiếp bởi hệ điều hành. Nhân thực hiện việc tạo luồng, lập thời biểu, và
quản lý không gian nhân. Luồng người dùng:
Được hỗ trợ dưới nhân và được cài đặt bởi thư viện luồng tại cấp người dùng.
Việc tạo luồng và lập thời biểu được thực hiện trong không gian người dùng mà không cần sự can thiệp của nhân.
Hai loại luồng
13
Java Simplified / Session 22 / 14 of 45
Java là một trong số nhỏ ngôn ngữ cung cấp sự hỗ trợ tại cấp ngôn ngữ cho việc tạo và quản lý luồng.
Tuy nhiên, vì các luồng được quản lý bởi máy ảo Java (JVM), không bởi một thư viện cấp người dùng hay nhân.
Một chương trình Java có ít nhất 1 Thread, nó được gọi thực hiện khi phương thức main chạy (như một luồng đơn trong máy ảo Java)
-> Main Thread. Ngoài ra, Java cung cấp các lệnh cho phép người phát triển
tạo và thao tác các luồng điều khiển bổ sung trong chương trình
Thread in Java
14
Java Simplified / Session 22 / 15 of 4515
Every Thread has a state and a Thread can be in one of these six states. new. A state in which a thread has not been started. runnable. A state in which a thread is executing. blocked. A state in which a thread is waiting for a lock to
access an object. waiting. A state in which a thread is waiting indefinitely for
another thread to perform an action. timed__waiting. A state in which a thread is waiting for up
to a specified period of time for another thread to perform an action.
terminated. A state in which a thread has exited.
Six states of Thread
Java Simplified / Session 22 / 16 of 45
Tạo tuyến đoạn mới:Thread newThread = new Thread(“threadName“); Kích hoạt đoạn tuyến khởi độngnewThread.start();
Khi tuyến đoạn ở trạng thái New thì chỉ có phương thức start() được gọi, nếu không sẽ có ngoại lệ IllegalThreadStateException được đưa ra
The New Thread State
16
Java Simplified / Session 22 / 17 of 45
Một tuyến đoạn ở trạng thái runnable mỗi khi phương thức start() của nó được kích hoạt.
Khi đó: mã lệnh trong phương thức run() có thể được xử lý bất kỳ khi nào giành được quyền xử lý từ hệ điều hành.
The Runnable thread state
17
Java Simplified / Session 22 / 18 of 45
Một tuyến đoạn ở not runnable state (blocked) khi: Phương thức sleep() của tuyến đoạn được gọi:
Tuyến đoạn sẽ tạm dừng sau một số ms xác định. Tuyến đoạn gọi phương thức wait() của một đối
tượng: Tuyến đoạn sẽ not runnable cho tới khi phương thức notify() hoặc notifyAll() được gọi từ một tuyến đoạn khác.
Tuyến đoạn bị blocked() bởi một thao tác vào/ra. Tuyến đoạn sẽ not runnable cho tới khi hoạt động vào ra hoàn thành.
The not Runnable Thread State
18
Java Simplified / Session 22 / 19 of 4519
A thread có thể dead or alive. Dead khi phương thức run() hoàn thành việc xử lý. Dead khi gán giá trị null cho đối tượng
Phương thức isAlive(): xác định một thread còn sống hay ko
Một thread ở trạng thái dead không thể được khởi động lại.
The Dead Thread State
Java Simplified / Session 22 / 20 of 45
Different thread states
New Thread(BORN)
READY
RUNNING
DEAD
SLEEPING
WAITING BLOCKED
20
Java Simplified / Session 22 / 21 of 4521
Main Thread
• Mỗi khi chạy một ứng dụng trong java thì đã có một thread.
• Đây là thread chính, nó thực thi các dòng lệnh trong method : public static void main . Đây là một điểm nhập bắt buộc cho mọi ứng dụng độc lập.
main thread : Tuyến đoạn đầu tiên thực hiện trong ứng dụng đa tuyến đoạn, được tạo ra tự động
Java Simplified / Session 22 / 22 of 4522
Main Thread• currentThread(): phương thức được dùng để truy
nhập vào main thread.
public static void main(String args[]) { Thread t= Thread.currentThread(); System.out.println(" The current thread: " + t); t.setName("MainThread"); System.out.println(“The current thread after name change:”+ t);
…}
Java Simplified / Session 22 / 23 of 4523
Có thể 2 cách: Extend the java.lang.Thread classoverride the run() method of the Thread class. Implement the java.lang.Runnable interfacedefine the run() method.
Create Thread
Java Simplified / Session 22 / 24 of 45
Lớp java.lang.Thread cung cấp các phương thức quản lý, kiểm soát độ ưu tiên của tuyến đoạn : khởi động (start()), tạm dừng (suspend()), phục hồi (resume()) và dừng hẳn (stop()).
Để sử dụng lớp Thread là thừa kế lớp này và nạp chồng phương thức run(): Nó được gọi khi khởi động tuyến đoạn lần đầu. Một tuyến đoạn có thể thực hiện một số tác vụ hữu ích
ở hậu trường
Dùng Thread class
24
Java Simplified / Session 22 / 25 of 45
class C1 extends Thread { public C1(){this.start();} public void run(){...} } void start(): Gọi một thread khởi độngThe start() method returns immediately after starting the new thread of control, without waiting for the thread to terminate
Dùng Thread class -
25
Java Simplified / Session 22 / 26 of 45
public class HelloThread extends Thread { public void run() {System.out.println("Hello from ABC thread"); } public static void main(String args[]) { (new HelloThread()).start(); System.out.println("Thread has been started");} }
Thread class, ex
26(new HelloThread()).run();
Java Simplified / Session 22 / 27 of 45
Creating and Running Threads
27
Java Simplified / Session 22 / 28 of 45
final boolean isAlive(): kiểm tra thread còn chạy không.
final String getName(): trả về tên của thread.
final void setName(String name): thiết đặt tên cho thread
Some methods of thread class
28
Java Simplified / Session 22 / 29 of 45
Ex MultiThread
29
class Thread_ex1 extends Thread {public static void main(String args[]) {Thread_ex1 Objex = new Thread_ex1();Objex.create();System.out.println("This is the main thread"); }public void create() { Thread Objth1 = new Thread(this); Thread Objth2 = new Thread(this); Thread Objth3 = new Thread(this); Objth1.start(); Objth2.start(); Objth3.start(); }
public void run() { while (true) { try { System.out.println("This is the child thread");
Thread.sleep(1000); } catch(InterruptedException e)
{ }}
}}
Java Simplified / Session 22 / 30 of 45
Mỗi Thread tạo ra đều thực thi các tác vụ giống nhau (theo run())
Muốn mỗi Thread thực hiện một tác vụ khác nhau? Tạo các method riêng cho các thread Tạo constructor, giá trị truyền vào khác nhau Tạo các thread ở các class khác nhau, viết run()
riêng cho mỗi thread.
Ex MultiThread
30
Java Simplified / Session 22 / 31 of 45
class TichTac extends Thread { String word; int delay; TichTac(String s, int d) { word =s; delay=d; } public void run() { try { while (true) { System.out.println(word+" "); sleep(delay); } } catch(InterruptedException
e) { System.out.print("Stop ct"); return; } } public static void main(String[] args) { new TichTac("Tich",330).start(); new TichTac("Tac",1000).start(); new TichTac(“tac",500).start(); } }
Ex, pingpong
31
Java Simplified / Session 22 / 32 of 45
private static class Tinh extends Thread {public void run() {…}}…Tinh[] worker = new Tinh[numberOfThreads]; for (int i = 0; i < numberOfThreads; i++)
{ worker[i] = new Tinh( i ); worker[i].start();
}
MultiThread using Array
32
Java Simplified / Session 22 / 33 of 45
Ex, MultiThread using Array
33
public class arrThread_ex1 {private static class Tinh extends Thread { int id; public Tinh(int id) { this.id = id; } public void run() { int count = countEven(1,1000); System.out.println("Thread " + id + " counted " + count); } } public static void main(String[] args) throws InterruptedException { Scanner TextIO = new Scanner (System.in); int numThr = 0; System.out.print("How many threads: (from 1 to 20)?"); numThr = TextIO.nextInt(); System.out.println("\nCreating " + numThr + " Even-counting thr"); Tinh[] worker = new Tinh[numThr]; for (int i = 0; i < numThr; i++) { worker[i] = new Tinh( i ); worker[i].start(); } System.out.println("Threads have been created and started."); }
private static int countEven(int min, int max) { int count = 0; for (int i = min; i <= max; i++) if (i % 2 ==0) count++; return count; }
Java Simplified / Session 22 / 34 of 45
không thể được nếu tạo ứng dụng đa tuyến đoạn bằng cách thừa kế từ lớp Thread.
Một giải pháp: thực thi giao tiếp java.lang.Runnable
Đa kế thừa trong Thread
34
Java Simplified / Session 22 / 35 of 45
Interface Runnable định nghĩa duy nhất một phương thức run(). Các lớp thực thi giao tiếp này chỉ ra rằng chúng
có thể chạy độc lập như một tuyến đoạn riêng. Báo hiệu các lớp thực thi giao tiếp này có thể
chạy như các tuyến đoạn. Có thể thừa kế từ một lớp khác - đa kế thừa Cùng một đối tượng Runnable có thể được truyền
cho nhiều tuyến đoạn, vì vậy một số tuyến đoạn tương tranh có thể sử dụng chung mã và thao tác trên cùng dữ liệu.
Dùng Interface Runnable
35
Java Simplified / Session 22 / 36 of 45
class C2 implements Runnable { public C2()
{Thread t = new Thread(this);} public void run(){...} }
Dùng Interface Runnable
36
Java Simplified / Session 22 / 37 of 45
public class HelloRunnable implements Runnable { public void run()
{ System.out.println("Hello from a thread!"); } public static void main(String args[])
{ (new Thread(new HelloRunnable())).start(); }}
Runnable, ex
37
Java Simplified / Session 22 / 38 of 45
Ex: Interface Runnable
38
class Run_ex1 implements Runnable {public static void main(String args[]) {Run_ex1 Obj1 = new Run_ex1();Obj1.create();System.out.println("This is the main thread");}public void create() {Thread Obj2 = new Thread(this); Obj2.start(); }public void run() {while(true) {try { System.out.println("This is the child thread"); Thread.sleep(500); } catch(InterruptedException e) { } } }}
Java Simplified / Session 22 / 39 of 45
public class ex {public static void main(String[] args) throws InterruptedException {Runnable a = new Runnable (){@Override
public void run() {System.out.println("AAAAA");
}};
Runnable b = new Runnable (){@Override
public void run() {System.out.println("BBBBB" );
}};
Runnable c = new Runnable (){@Override
public void run() {System.out.println("CCCCCC");
}};
//Tao 3 Threads ta, tb,tcThread ta = new Thread(a, "threadA"); ta.start(); Thread.sleep(1000); Thread tb = new Thread(b, "threadB"); tb.start(); Thread.sleep(1000); Thread tc = new Thread(c, "threadC"); tc.start(); Thread.sleep(1000); }}
Ex: not implement Runnable Interface
39
Java Simplified / Session 22 / 40 of 45
final void join() throws InterruptedException:
làm cho thread gọi join() (thread khác) phải ngưng hoạt động và chờ trong một khoảng thời gian, hoặc đến khi thread này kết thúc thì mới tiếp tục hoạt độngMean: another thread calls thrd.join(), that other thread will go to sleep until thrd terminates. If thrd is already dead when thrd.join() is called, then it simply has no e ect ff
Some methods of thread class
40
Java Simplified / Session 22 / 41 of 45
final void join(m) throws InterruptedException
A call to thrd.join(m) will wait until either thrd hasterminated or until m milliseconds have elapsed.Ex: System.out.print("Running the thread ");thrd.start();while (thrd.isAlive()) {try { thrd.join(2000); System.out.print(".");
} catch (InterruptedException e) { } }System.out.println(" Done!");
Some methods of thread class
41
Java Simplified / Session 22 / 42 of 45
static void yield(): giành lấy quyền thực thi của tuyến đoạn hiện hành cho một trong các tuyến đoạn khác (sleep).
final boolean isDaemon(): kiểm tra Daemon thread.
static int activeCount(): trả về số thread đang active.
static void sleep(): đưa tiến đoạn hiện hành vào trạng thái nghỉ tối thiểu là ms
Some methods of thread class
42
Java Simplified / Session 22 / 43 of 45
Hiện thị giá trị number giảm dần: 100->1(extend: Hình ảnh đồng hồ đếm ngược)
File Thread_App_ex.java
MultiThread trong Applet - ex
43
Java Simplified / Session 22 / 44 of 45
Consider a simple class called Counterclass Counter { private int c = 0; public void increment() { c++; } public void decrement() { c--; } public int value() { return c; }}
Synchronization
44
Java Simplified / Session 22 / 45 of 45
The single expression c++ can be Retrieve the current value of c. Increment the retrieved value by 1. Store the incremented value back in c.
Ex, Thread A invokes increment at about the same time Thread B invokes decrement. If the initial value of c is 0, Thread A: Retrieve c. Thread B: Retrieve c. Thread A: Increment retrieved value; result is 1. Thread B: Decrement retrieved value; result is -1. Thread A: Store result in c; c is now 1. Thread B: Store result in c; c is now -1.
Synchronization
45
Java Simplified / Session 22 / 46 of 45
Khi làm việc với nhiều Thread, có thể có một số Thread muốn sử dụng cùng tài nguyên tại cùng 1 time. Khi hai tuyến đoạn cần sử dụng cùng một đối tượng, có
một khả năng có các thao tác đan xen nhau làm phá hỏng dữ liệu => Race condition. ex,
Cần phải có sự đồng bộ - Synchronization.exp, Tại một time t chỉ có 1 thread sử dụng tài nguyên. Monitor: Chỉ có 1 Thread có được monitor tại 1 time. Các
Thread khác muốn có được monitor phải chờ đợi.
Synchronization
46
Java Simplified / Session 22 / 47 of 45
Sử dụng phương thức chiếm dụng đối tượng: Nếu một đối tượng bị phong tỏa (used) bởi một tuyến
đoạn nào đó thì chỉ có tuyến đoạn đó mới được truy cập tới đối tượng.
Nếu một tuyến đoạn kích hoạt một phương thức synchronized trên một đối tượng, đối tượng đó sẽ bị chiếm dụng bởi tuyến đoạn kích hoạt.
Khi đối tượng được giải phóng, một tuyến đoạn khác mới được kích hoạt synchronized trên cùng đối tượng
synchronized(Obj);Note that constructors cannot be synchronized
Method synchronized()
47
Java Simplified / Session 22 / 48 of 45
TestUnsyn.java
ex
48
public static void main(String[] args) throws Exception { final TestUnsyn tus = new TestUnsyn(); Runnable runA = new Runnable() { public void run() { tus.doAction(3); } }; Thread ta = new Thread(runA, "threadA"); ta.start(); Thread.sleep(2000); Runnable runB = new Runnable() { public void run() { tus.doAction(7); } }; Thread tb = new Thread(runB, "threadB"); tb.start(); }
public synchronized void doAction(int val) {int taskID;String thrName = Thread.currentThread().getName();System.out.println(thrName + ":entering doAction()");taskID = val; System.out.println(thrName + ":doAction() " + taskID); try { Thread.sleep(1000); } catch (InterruptedException x) { } System.out.println(thrName + ": doAction() sleep after taskID " + taskID); System.out.println(thrName + ": leaving performATask() " + taskID); }
Java Simplified / Session 22 / 49 of 45
Lệnh synchronized cho phép đồng bộ hóa một đối tượng thay cho phương thức synchronized
Cú pháp synchronized (expr) {//this code will execute in one thread at//a time and someObject will be locked.
}
Lệnh synchronized
49
Java Simplified / Session 22 / 50 of 45
Ex1:synchronized (color) { int myColorInt = color.getRGB(); //may be another thread invoke color.set() String myColorName = color.getName();}
Lệnh synchronized, ex
50
Ex2: synchronized(tsc) {if ( tsc.getValue() == 0 )doSomething();
}
Java Simplified / Session 22 / 51 of 45
Cơ chế chiếm dụng đồng bộ hóa ngăn cho các tuyến đoạn chồng chéo nhau.
Các tuyến đoạn vẫn có thể trao đổi thông tin với nhau, sử dụng các phương thức: wait() notify() notifyAll()
Các phương thức này được định nghĩa trong lớp Object và được thừa kế từ các lớp Object.
Methods: wait , notify
51
Java Simplified / Session 22 / 52 of 45
public final void wait(long timeout) throws InterruptedException: Tuyến đoạn hiện thời chờ cho tới khi được cảnh báo hoặc một
khoảng thời gian timeout nhất định. Nếu timeout bằng 0 thì phương thức sẽ chỉ chờ cho tới khi có
cảnh báo về sự kiện. public final void notify()
Cảnh báo ít nhất một tuyến đoạn đang chờ một điều kiện nào đó thay đổi trước khi có thể gọi phương thức wait nào đó.
public final void notifyAll() Cảnh báo tất cả các tuyến đoạn đang chờ một điều kiện thay đổi Trong số các tuyến đoạn đã được cảnh báo, tuyến đoạn nào có
độ ưu tiên cao nhất thì sẽ chạy trước tiên.
Methods: wait , notify
52
Java Simplified / Session 22 / 53 of 45
Synchronization with wait & notify
53
Java Simplified / Session 22 / 54 of 45
public class Wait_Noti extends Thread { public static void main(String args[]) throws Exception { Thread notiThread = new Wait_Noti(); notiThread.start(); // cont to run()// wait thread an event execute synchronized (notiThread) { notiThread.wait(7000); } // wait() is done System.out.println ("The wait is over"); }
Ex: wait , notify
54
Java Simplified / Session 22 / 55 of 45
public void run() { System.out.println (" Click enter to stop waiting thread"); try { System.in.read(); System.out.println ("Stop");
} catch (java.io.IOException ioe) { System.out.println (" Over"); } // Notify any threads waiting on this thread synchronized (this) { this.notifyAll(); }
} }
Ex: wait , notify
55
Java Simplified / Session 22 / 56 of 45
Bài toán Producer – Consumer. Product: get set(i)
Producer: set Product Consumer: get Product
Ex: Synchonized with wait, notify
56
Java Simplified / Session 22 / 57 of 45
public class Synch_ex {public class Product {private int view = 0;public boolean isRemainingview;public int get() {//print onto screenSystem.out.println("\tConsumer get " + this.view);return view; }public void set(int piview) {this.view = piview;System.out.println(“Producer set" + this.view);
}} //end class Product
public class Producer extends Thread {private Product sp;Producer(Product pProduct) {sp = pProduct; }public void run() {for(int i = 0; i < 10; i++) {sp.set(i);
try {Thread.sleep(500);
} catch (InterruptedException e) { }
}}
}//end class Producer
Ex, Non Synchnozied
57
Java Simplified / Session 22 / 58 of 45
public class Consumer extends Thread {private Product sp;Consumer(Product pProduct) {sp = pProduct; }public void run() {for(int i = 0; i < 10; i++) {
sp.get();try {Thread.sleep(500);
} catch (InterruptedException e) {
}}
}
}//end class Consumer
public static void main(String[] args) {Synch_ex t = new Synch_ex ();Product s = t.new Product();//2 thread cung dung chung doi tuong s thuoc class ProductProducer p = t.new Producer(s);Cosumer c = t.new Consumer(s);p.start();c.start();
}}//end class Synch_ex
Ex, cont
58
Java Simplified / Session 22 / 59 of 45
public synchronized int get() {while(isRemainingContents == false) {try {wait();} catch (InterruptedException e) {}
}
isRemainingContents = false;//print onto screenSystem.out.println("\tConsumer get " + this.view);//Notify Producer to produce new viewnotifyAll();return view;}
Ex, Synchonoized (syncho_full.java) public synchronized void set(int piview ) {while(isRemainingContents == true) {try {wait();} catch (InterruptedException e) {}
}this.view = piview;isRemainingContents = true;//print onto screenSystem.out.println(“Producer set " + this.view);//Notify Consumer get this viewnotifyAll();}}
59
Java Simplified / Session 22 / 60 of 45
Java gán cho mỗi tuyến đoạn một độ ưu tiên để xác định cách tuyến đoạn đó được xử lý như thế nào so với các tuyến đoạn khác.
Mỗi thread mới thừa kế quyền ưu tiên mà thread đã tạo ra nó.
A thread with a greater priority value will be run in preference to a thread with a smaller priority
Hằng số: public static final int MIN_PRIORITY = 1; public static final int NORM_PRIORITY = 5; public static final int MAX_PRIORITY = 10;
Thread PRIORITY
60
Java Simplified / Session 22 / 61 of 45
Phương thức: setPriority(): thiết lập độ ưu tiên của tuyến đoạn hiện thời getPriority(). nhận về độ ưu tiên của một tuyến đoạn public static void sleep(long ms) throws InterruptedException
đưa tiến đoạn hiện hành vào trạng thái nghỉ tối thiểu là ms (mili giây).
Ex , Piority_Demo.java
Thread PRIORITY
61
Java Simplified / Session 22 / 62 of 45
Deadlock: Một kiểu lỗi đặc biệt cần phải tránh có liên quan đến đa nhiệm, Xảy ra khi hai tuyến đoạn có một sự phụ thuộc xoay vòng trên
một cặp đối tượng đồng bộ. Ví dụ, một tuyến đoạn chiếm dụng đối tượng X và một tuyến
đoạn chiếm dụng đối tượng Y. Nếu tuyến đoạn chiếm dụng X cố gắng gọi bất kỳ phương
thức đồng bộ trên Y, thì nó sẽ bị phong tỏa. Nếu tuyến đoạn chiếm dụng Y gọi phương thức đồng bộ
trên X, tuyến đoạn sẽ chờ vô hạn. Tuyến đoạn này chờ tuyến đoạn kia giải phóng đối tượng mà
đối tượng kia đang bị chiếm dụng và ngược lại -> chờ đợi lẫn nhau (hoài vọng)
Bế tắc-Deadlock
62
Java Simplified / Session 22 / 63 of 45
Cần hạn chế deadlock: Đưa ra và cải tiến việc cấp phát, thu hồi tài nguyên cho các thread khá nhiều thuật toán cải tiến việc này
deadlock_ex.java
Ex, Deadlock
63
Java Simplified / Session 22 / 64 of 45
Khi gọi phương thức Thread.sleep(int): đặt tuyến đoạn vào trạng thái nghỉ trong một khoảng thời gian xác định nào đó.
Tuy nhiên để kích hoạt một tuyến đoạn sớm hơn ta phải sử dụng ngắt tuyến đoạn. Phương thức interrupt(). Cần một tuyến đoạn khác tham chiếu tới tuyến
đoạn hiện thời.
Interrupt a Thread
64
Java Simplified / Session 22 / 65 of 45
public class vd1 extends Thread { //Run method is executed when thread first started public void run() { System.out.println ("I feel sleepy. Wake me in eight hours"); try { // Sleep for eight hours Thread.sleep( 1000*60 ); System.out.println ("That was a nice nap"); } catch (InterruptedException ie) { System.err.println ("Just five more minutes...."); } }
//Main method to create and start threads public static void main(String args[]) throws java.io.IOException { // Create a 'sleepy' thread Thread sleepy = new vd1(); // Start thread sleeping sleepy.start(); // Prompt user and wait for input System.out.println ("Press enter to interrupt the thread"); System.in.read(); // Interrupt the thread sleepy.interrupt(); } }
Ex: interrupt
65
Java Simplified / Session 22 / 66 of 45
Put to sleep using sleep() method Is waiting because wait() method was
called Explicitly yielded using yield() method Blocked for file I/O
Conditions thread not execute
If thread is: Not of highest priority
66
Java Simplified / Session 22 / 67 of 45
Đôi khi cần thiết phải kết thúc một tuyến đoạn trước khi tác vụ của nó hoàn thành. Phương thức Thread.stop(). Đòi hỏi tuyến đoạn điều khiển duy trì một tham
chiếu tới tuyến đoạn mà nó muốn dừng.
Stop a Thread
67
Java Simplified / Session 22 / 68 of 45
public class vd1 extends Thread { // Run method is executed when thread first started public void run() { int count = 1; System.out.println ("I can count. Watch me go!"); for (;;) { // Print count and increment it System.out.print (count++ + " "); // Sleep for half a second try { Thread.sleep(1000); } catch(InterruptedException ie) {} } }
// Main method to create and start threads public static void main(String args[]) throws java.io.IOException { // Create and start counting thread Thread counter = new vd1(); System.out.println ("Press any enter to stop the thread ounting"); counter.start(); // Prompt user and wait for input System.in.read(); // Interrupt the thread counter.stop(); } }
Ex: stop Thread
68
Java Simplified / Session 22 / 69 of 45
Review: Cycle of Thread
69
Java Simplified / Session 22 / 70 of 45
Khi cần phải xử lý với nhiều Threads -> cần phải tổ chức dạng mảng… -> việc xử lý nhiều.
Nhóm các tuyến đoạn với nhau: áp dụng một thao tác trên nhóm mà không phải thực hiện thao tác trên từng tuyến đoạn riêng lẻ.
Java API hỗ trợ khả năng làm việc với các nhóm tuyến đoạn nhờ lớp ThreadGroup. biểu diễn một tập hợp các tuyến đoạn, và cung cấp các phương thức tác động nhanh trên từng
tuyến đoạn riêng trong nhóm. Nó còn cung cấp các cách thức để tập hợp các thông tin về
các tuyến đoạn có liên quan nói chung. Nếu cần truy xuất tới từng tuyến đoạn riêng lẻ, ta có thể
truy xuất thông qua ThreadGroup.
ThreadGroup
70
Java Simplified / Session 22 / 71 of 45
Constructor: public ThreadGroup(String name) throws
java.lang.SecurityException Tạo ra một nhóm tuyến đoạn mới, có tên được xác định bởi name.
ThreadGroup(ThreadGroup parentGroup,String name) throws java.lang.SecurityException
Tạo ra một nhóm tuyến đoạn mới name là nhóm con của ParentGroup Ex:ThreadGroup parent = new ThreadGroup("parent"); ThreadGroup subgroup = new ThreadGroup(parent, "sub");
ThreadGroup
71
Java Simplified / Session 22 / 72 of 45
Sử dụng một ThreadGroup Một nhóm tuyến đoạn có thể được sử dụng như một tuyến
đoạn bình thường. Ta có thể tạm dừng, phục hồi, ngắt hoặc dừng nhóm tuyến
đoạn bằng cách gọi phương thức thích hợp. Các phương thức
int activeCount(): trả về số tuyến đoạn trong nhóm, và các nhóm con.
int activeGroupCount(): trả về số nhóm con các tuyến đoạn
boolean allowThreadSuspension(): chỉ ra tuyến đoạn bị tạm ngừng hay không.
ThreadGroup
72
Java Simplified / Session 22 / 73 of 45
public class GroupDemo implements Runnable{ public static void main(String args[]) throws Exception {ThreadGroup parent = new ThreadGroup("parent"); ThreadGroup subgroup = new ThreadGroup(parent, "subgroup");Thread t1 = new Thread ( parent, new GroupDemo() ); t1.start(); Thread t2 = new Thread ( parent, new GroupDemo() ); t2.start(); Thread t3 = new Thread ( subgroup, new GroupDemo() ); t3.start(); Thread t4 = new Thread ( subgroup, new GroupDemo() ); t4.start(); // Dump the contents of the group to System.out parent.list(); System.exit(0); } public void run(){
while (true) { Thread.yield(); } } }
Ex: ThreadGroup
73
Java Simplified / Session 22 / 74 of 45
Two types of threads in Java: User threads: created by the user Daemon threads: threads that work in the
background providing service to other threadse.g. – the garbage collector thread
When user thread exits, JVM checks to find out if any other thread is running. If there are, it will schedule the next thread. If the only executing threads are daemon
threads, it exits.
Why need Daemon
Daemon threads
74
Java Simplified / Session 22 / 75 of 45
We can set a thread to be a Daemon if we do not want the main program to wait until a thread ends.
Thread class has two methods to deal with Daemon threads: public final void setDaemon(boolean value) : sets a thread to be a daemon thread
public final boolean isDaemon() : checks if the given thread is a daemon thread
Ex: Objex.isDaemon()
Daemon threads Contd…
75
Java Simplified / Session 22 / 76 of 45
Daemon threads, ex
An example
class TestDaemon implements Runnable{
Thread Objth1,Objth2; public TestDaemon() {
Objth1 = new Thread(this);Objth1.start();Objth2 = new Thread(this);Objth2.setDaemon(true);
} public void run() {
System.out.println(Thread.activeCount());System.out.println(Objth1.isDaemon());System.out.println(Objth2.isDaemon());
}public static void main(String args[])
{new TestDaemon();
}}
Java Simplified / Session 22 / 77 of 45
Đa tuyến hay được ứng dụng trong các chương trình Server: Đòi hỏi tại một thời điểm chấp nhận nhiều kết nối
đến từ các Client và xử lý cho nhiều Client tai một thời điểm
Mô hình
Sử dụng Thread trong các chương trình Server
77
Java Simplified / Session 22 / 78 of 45
Ex, Chat theo TCP
Sử dụng Thread để gửi /nhận dữ liệu
78
Java Simplified / Session 22 / 79 of 45
Multithreading allows programmers to write efficient programs that make the maximum use of the CPU.
Java provides built-in support for multithreading in the form of classes and interfaces.
When Java programs are executed, there is already one thread that is running and it is the main thread. This main thread is important for two reasons: It is the thread from which child threads will be created. Program is terminated when the main thread stops execution.
Thread objects can be created in two ways: Declare the class to be a sub-class of the Thread class where we need to
override the run() method of the Thread class. Declare a class that implements the Runnable interface. Then define the run() method.
Each thread in a Java program is assigned a priority, and the Java Virtual Machine never changes the priority of a thread.
Summary
79