JAVA~多线程:sleep、yield方法

时间:2023-12-16 13:07:56

sleep不考虑其它线程的优先级

yield让位给相同或更高优先级的线程

sleep

JAVA~多线程:sleep、yield方法

yield

JAVA~多线程:sleep、yield方法

package multiThread2;

public class TestThread042Yield {
    public static void main(String[] args) {
        MyThread3 t1 = new MyThread3("t1");
        MyThread3 t2 = new MyThread3("t2");
        MyThread3 t3 = new MyThread3("t3");
        t1.setPriority(Thread.MIN_PRIORITY);
        t2.setPriority(Thread.NORM_PRIORITY);
        t3.setPriority(Thread.MAX_PRIORITY);
        t1.start();
        t2.start();
        t3.start();
    }
}

class MyThread3 extends Thread {
    MyThread3(String s) {
        super(s);
    }
    public void run() {
        for (int i = 1; i <= 100; i++) {
            System.out.print("");
            if (i % 10 == 0) {
//                try {
//                    sleep(10);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                yield();
                System.out.println(this.getName() + ":"+ i);
            }
        }
    }
}