Java Thread yield()

package Thread;

public class MyThread implements Runnable{

	protected	   int countDown = 10;		
	private static int taskCount = 0;
	private final  int id = taskCount++;
	
	public MyThread(){}
	public MyThread(int countDown){
		this.countDown = countDown;
	}
	
	public String status(){
		return "#"+id+"("+(countDown>0?countDown+"),":"LiftOff"+")");
	}
	
	@Override
	public void run() {
		
		while(countDown-->0){
			System.out.print(status());
			<span style="color:#ff0000;">Thread.yield();	</span>				//here
		}
	}
	
	public static void main(String args[]){
		
		MyThread mt = new MyThread();
		mt.run();
	}

}

output  #0(9),#0(8),#0(7),#0(6),#0(5),#0(4),#0(3),#0(2),#0(1),#0(LiftOff)  



package Thread;

public class BasicThread implements Runnable{
	
	private static int taskCount;
	private final int id = taskCount++;
	BasicThread(){
		System.out.println("BasicThread started,ID = "+id);
	}
	@Override
	public void run() {
		
		System.out.println("Stage 1....,ID = "+id+"  "+Thread.currentThread().getName());
		<span style="color:#ff0000;">Thread.yield();	</span>	
		System.out.println("Stage 2....,ID = "+id+"  "+Thread.currentThread().getName());
		<span style="color:#ff0000;">Thread.yield();</span>
		System.out.println("BasicThread ended, ID = "+id+"  "+Thread.currentThread().getName());
		
	}
	
	public static void main(String args[]){
		
		for(int i=0;i<5;i++){
			Thread thread = new Thread(new BasicThread());
			thread.start();
		}			
	}
}

output::  

BasicThread started,ID = 0
BasicThread started,ID = 1
Stage 1....,ID = 0  Thread-0
Stage 1....,ID = 1  Thread-1
BasicThread started,ID = 2
Stage 2....,ID = 0  Thread-0
Stage 2....,ID = 1  Thread-1
BasicThread started,ID = 3
BasicThread ended, ID = 1  Thread-1
BasicThread ended, ID = 0  Thread-0
Stage 1....,ID = 3  Thread-3
BasicThread started,ID = 4
Stage 2....,ID = 3  Thread-3
Stage 1....,ID = 4  Thread-4
Stage 2....,ID = 4  Thread-4
BasicThread ended, ID = 3  Thread-3
BasicThread ended, ID = 4  Thread-4
Stage 1....,ID = 2  Thread-2
Stage 2....,ID = 2  Thread-2
BasicThread ended, ID = 2  Thread-2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值