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

你可能感兴趣的:(多线程)