A ผลตอบแทน() เมธอดเป็น คงที่ วิธีการ กระทู้ คลาสและสามารถหยุดเธรดที่กำลังรันอยู่และจะให้โอกาส เธรดการรออื่น ๆ ที่มีลำดับความสำคัญเท่ากัน หากในกรณีที่ไม่มีเธรดที่รอหรือหากเธรดที่รอทั้งหมดมีลำดับความสำคัญต่ำ จากนั้นเธรดเดียวกันจะดำเนินการต่อไป ข้อดีของ yield() วิธีคือการได้รับโอกาสในการรันเธรดอื่นที่รอ ดังนั้นหากเธรดปัจจุบันของเราใช้เวลาในการรันและจัดสรรโปรเซสเซอร์ให้กับเธรดอื่นมากขึ้น
ไวยากรณ์
public static void yield()
ตัวอย่าง
class MyThread extends Thread {
public void run() {
for (int i = 0; i < 5; ++i) {
Thread.yield(); // By calling this method, MyThread stop its execution and giving a chance to a 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());
}
} ผลลัพธ์
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