yield() là phương thức static của lớp Thread dừng luồng đang thực thi và nhường cơ hội cho các luồng chờ cùng độ ưu tiên. Nếu không có luồng chờ hoặc tất cả luồng chờ có độ ưu tiên thấp, luồng hiện tại tiếp tục thực thi. Lợi ích của yield() là cho phép các luồng chờ khác thực thi nếu luồng hiện tại tốn nhiều thời gian.
Cú pháp
public static void yield()
Ví dụ
class MyThread extends Thread {
public void run() {
for (int i = 0; i < 5; ++i) {
Thread.yield(); // MyThread dừng và nhường cho main thread
System.out.println("Thread started: " + Thread.currentThread().getName());
}
System.out.println("Thread ended: " + Thread.currentThread().getName());
}
}
public class YieldMethodTest {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
for (int i = 0; i < 5; ++i) {
System.out.println("Thread started: " + Thread.currentThread().getName());
}
System.out.println("Thread ended: " + Thread.currentThread().getName());
}
}
Kết quả
Thread started:main Thread started:Thread-0 Thread started:main Thread started:Thread-0 Thread started:main Thread started:Thread-0 Thread started:main Thread started:Thread-0 Thread started:main Thread started:Thread-0 Thread ended:main Thread ended:Thread-0