[LTM] Chương 6.5: Create threads (Tạo luồng)

Thread in Java


  • 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
Create Thread

Có thể 2 cách:
Extend the java.lang.Thread class
override the run() method of the Thread class.
Implement the java.lang.Runnable interface
define the run() method.


Cách 1: Dùng Thread class

 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



class C1 extends Thread 
   public C1(){this.start();} 
   public void run(){...} 
}
void start(): Gọi một thread khởi động
The start() method returns immediately after starting the new thread of control, without waiting for the thread to terminate 

Thread class, ex
Start() vs. run() 
Note that calling HelloThread.start() is very different from calling HelloThread.run():
Calling HelloThread.run() would execute the run() method in the same thread, rather thancreating a new thread. 
This means that all the work of the run() will be done before the computer moves on to the statements that follow the call to HelloThread.run(). 
=>There is no parallelism and no indeterminacy

Creating and Running Threads
Ex MultiThread (same task)
Ex MultiThread:

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, Multithreads. 

Ex, MyThread_parent, MyThread_child

It is important to note that these messages can be printed in either order. 
The two threads run simultaneously and will compete for access to standard output, so that they can print their Messages
In single-threaded program, things happen in a definite, predictable order from beginning to end. 
In a multi-threaded program, there is a fundamental indeterminacy. You can’t be sure what order things will happen in

MultiThread using Array
Ex, MultiThread Array (same task)
ex :
MultiThread in multitask, 
ex: CountUC_Thread
int processors = Runtime.getRuntime().availableProcessors();
 long start = System.currentTimeMillis();
long elapsedTime = System.currentTimeMillis() - start;

Some methods of thread class 

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 động
Mean: 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 effect 

final void join(m) throws InterruptedException
A call to thrd.join(m) will wait until either thrd has
terminated 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!");

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

Cách 2: Dùng Interface Runnable 
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. 

Cách định nghĩa
class C2 implements Runnable 
   public C2()
{Thread t = new Thread(this);} 
   public void run(){...} 
}
Runnable, ex
Ex: Interface Runnable 
Ex: not implement Runnable Interface

MultiThread trong Applet - ex
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