Thread.yeild()
让出CPU资源,使线程从运行状态变为就绪状态,和其他线程回到同一起跑线,让CPU重新选择,还有可能会被再一次选中。
实例:
package com.zw;
public class ThreadTest {
public static void main(String[] args) {
ThreadOne threadOne = new ThreadOne();
ThreadOne threadTwo = new ThreadOne();
Thread thread = new Thread(threadOne);
Thread thread1 = new Thread(threadTwo);
thread.start();
thread1.start();
}
}
class ThreadOne implements Runnable {
@Override
public void run() {
for (int i = 0; i < 50; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
if(i == 30)
{
Thread.yield();
System.out.println(Thread.currentThread().getName() + " 暂停 " + i);
}
}
}
}