Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ความสำคัญของเมธอด yield() ใน Java Thread


yield() เป็น static method ของคลาส Thread หยุดเธรดปัจจุบันชั่วคราวให้โอกาส เธรดอื่นที่รออยู่และมี priority เท่ากัน หากไม่มีเธรดรอ หรือเธรดรอมี priority ต่ำกว่า เธรดเดิมจะทำงานต่อ ข้อดีคือให้โอกาสเธรดอื่นรันเมื่อเธรดปัจจุบันใช้เวลานาน

ไวยากรณ์

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