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

Java Concurrency - เมธอด yield()

เมธอด yield()

เมธอดนี้พยายามให้ thread ที่สำคัญกว่าได้รันก่อน แทนที่ thread ที่ใช้เวลานานและไม่สำคัญ เมื่อ thread เรียก java.lang.Thread.yield() เป็นสัญญาณให้ thread scheduler หยุดการทำงานชั่วคราว Scheduler อาจยอมรับหรือไม่ยอมรับก็ได้

หาก thread เรียก yield() scheduler จะตรวจสอบว่ามี thread ที่มี priority เท่ากันหรือสูงกว่าหรือไม่ หากมี thread ปัจจุบันจะถูกย้ายไปสถานะ runnable/ready และให้ thread อื่นใช้ CPU แทน

Syntax

public static native void yield()

ตัวอย่าง

import java.lang.*;

class Demo extends Thread {
    public void run() {
        for (int i = 0; i < 3; i++)
            System.out.println("In control of " + Thread.currentThread().getName() + " thread");
    }
}

public class Demo_one {
    public static void main(String[] args) {
        Demo my_obj = new Demo();
        my_obj.start();
        for (int i = 0; i < 3; i++) {
            Thread.yield();
            System.out.println("In control of " + Thread.currentThread().getName() + " thread");
        }
    }
}

ผลลัพธ์

In control of main thread
In control of main thread
In control of main thread
In control of Thread-0 thread
In control of Thread-0 thread
In control of Thread-0 thread

คลาส Demo extends Thread มี run() วนลูปพิมพ์ชื่อ thread คลาส Demo_one มี main สร้าง Demo เริ่ม thread แล้ววนลูป 3 รอบ เรียก yield() และพิมพ์ชื่อ thread main

ข้อสังเกตสำคัญ

  • หลัง yield() thread จะแข่งกันขอ CPU resources ไม่มีวิธีกำหนดว่าใครจะรันก่อน
  • thread ที่ yield() จะเปลี่ยนจาก Running state เป็น Runnable state
  • yield() ใช้ได้เฉพาะ platform ที่รองรับ pre-emptive scheduling
  • ไม่มีการรับประกันว่า thread ที่ yield() จะได้รันอีกเร็วๆ นี้ ขึ้นกับ scheduling algorithm