首页 > 代码库 > 线程的礼让

线程的礼让

在线程操作中,可以使用yield()方法将一个线程的操作暂时让给其他线程执行:

class MyThread17 implements Runnable {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " run---->"
                    + i);
            if (i == 3) {
                System.out.println("Thread yield:");
                Thread.currentThread().yield();
            }
        }
    }
}

public class ThreadYieldDemo {
    public static void main(String[] args) {
        MyThread17 my = new MyThread17();
        Thread t1 = new Thread(my, "THread A");
        Thread t2 = new Thread(my, "THread B");
        t1.start();
        t2.start();
    }
}