Java Thread.yield方法

yield方法:让线程从运行状态进入到就绪状态,让其它相同优先级的线程获取执行权,但是执行yield()方法后,其它线程不一定会获取到执行权,也有可能当前线程能重新获取到执行权。如果yield()方法在同步模块中,执行yield()方法后,不会有锁的释放。

public class ThreadYield extends Thread {
	
	private String name;
	
	public ThreadYield(String name){
		this.name = name;
	}
	
	public void run() {
		for(int i = 0; i<10;i++){
			Thread.yield();
			System.out.println(name + "----- is runing:"+i);
		}
	}
	
	
	public static void main(String[] args) {
		
		ThreadYield thread1 = new ThreadYield("thread1");
		ThreadYield thread2 = new ThreadYield("thread2");
		thread1.start();
		thread2.start();
		
	}
	
	

}

执行结果:

thread2----- is runing:0
thread1----- is runing:0
thread2----- is runing:1
thread1----- is runing:1
thread2----- is runing:2
thread1----- is runing:2
thread2----- is runing:3
thread1----- is runing:3
thread2----- is runing:4
thread1----- is runing:4
thread2----- is runing:5
thread1----- is runing:5
thread2----- is runing:6
thread2----- is runing:7
thread1----- is runing:6
thread2----- is runing:8
thread1----- is runing:7
thread2----- is runing:9
thread1----- is runing:8
thread1----- is runing:9

阅读更多
个人分类: 多线程
上一篇Java中wait()与notify()方法的使用
下一篇Java Thread.sleep方法介绍
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭