6 sleep与yield的比较sleep
调用 sleep 会让当前线程从 Running 进入 Timed Waiting 状态(阻塞)
其它线程可以使用 interrupt 方法打断正在睡眠的线程,这时 sleep 方法会抛出 InterruptedException
睡眠结束后的线程未必会立刻得到执行
建议用 TimeUnit 的 sleep 代替 Thread 的 sleep 来获得更好的可读性
yield
调用 yield 会让当前线程从 Running 进入 Runnable 就绪状态,然后调度执行其它线程 。同时,该线程在就绪状态时,CPU可能会分配资源给它,使其进入运行态。
具体的实现依赖于操作系统的任务调度器
yield和线程优先级代码实例
//代码实例public class YieldAndPriority { public static void main(String[] args) { Runnable task1 = new Runnable() { @Override public void run() { int count = 0; //yield,让线程进入就绪态,CPU可能会调度该线程,使得该线程变为执行状态 Thread.yield(); while (true) { System.out.println("-------> task1 count=" + count++); } } }; Runnable task2 = new Runnable() { @Override public void run() { int count = 0; while (true) { System.out.println(" --------------------------------------> task2 count=" + count++); } } }; Thread t1 = new Thread(task1, "t1"); Thread t2 = new Thread(task2, "t2"); //设置优先级1-10 越大优先级越高 t1.setPriority(1); t2.setPriority(10); t1.start(); t2.start(); }}
//输出结果...--------------------------------------> task2 count=34436--------------------------------------> task2 count=34437--------------------------------------> task2 count=34438--------------------------------------> task2 count=34439--------------------------------------> task2 count=34440--------------------------------------> task2 count=34441--------------------------------------> task2 count=34442--------------------------------------> task2 count=34443--------------------------------------> task2 count=34444-------> task1 count=42407-------> task1 count=42408-------> task1 count=42409-------> task1 count=42410-------> task1 count=42411-------> task1 count=42412-------> task1 count=42413-------> task1 count=42414-------> task1 count=42415-------> task1 count=42416进程已结束,退出代码130