yield():线程让步,能让当前线程由“运行状态”进入到“就绪状态”,从而让其他具有相同优先级的等待线程获取执行权。
示例1:
public class ThreadA extends Thread{
public ThreadA(String name ){
super(name);
}
public synchronized void run(){
for(int i = 3; i < 9; i++){
System.out.printf("%s [%d]:%d\n", this.getName(), this.getPriority(), i);
if(i % 4 == 0){
Thread.yield();
}
}
}
public static void main(String[] args) {
ThreadA t1 = new ThreadA("t1");
ThreadA t2 = new ThreadA("t2");
t1.start();
t2.start();
}
}
运行结果:
t1 [5]:3
t1 [5]:4
t2 [5]:3
t2 [5]:4
t1 [5]:5
t1 [5]:6
t1 [5]:7
t1 [5]:8
t2 [5]:5
t2 [5]:6
t2 [5]:7
t2 [5]:8
示例二:
public class YieldLockTest {
private static Object obj = new Object();
static class ThreadA extends Thread{
public ThreadA(String name){
super(name);
}
public void run(){
synchronized (obj){
for(int i = 3; i < 8; i++){
System.out.printf("%s [%d]:%d\n", this.getName(), this.getPriority(), i);
if(i % 3 == 0){
Thread.yield();
}
}
}
}
public static void main(String[] args) {
ThreadA thread1 = new ThreadA("thread1");
ThreadA thread2 = new ThreadA("thread2");
thread1.start();
thread2.start();
}
}
}
运行结果:
thread1 [5]:3
thread1 [5]:4
thread1 [5]:5
thread1 [5]:6
thread1 [5]:7
thread2 [5]:3
thread2 [5]:4
thread2 [5]:5
thread2 [5]:6
thread2 [5]:7
结果说明:
(01) wait()是让线程由“运行状态”进入到“等待(阻塞)状态”,yield()是让线程由“运行状态”进入到“就绪状态”。
(02) wait()是会线程释放它所持有对象的同步锁,而yield()方法不会释放锁。
网友评论