Sleep 和yeild 区别

LiftOff类实现了Runnable。
import java.util.concurrent.TimeUnit;

public class LiftOff implements Runnable {

	protected int countDown = 10;
	private static int taskCount = 0;
	
	// define with "final" here that thread
	private final int id = taskCount++;

	public LiftOff(int countDown) {
		this.countDown = countDown;
	}

	public LiftOff() {
	}

	@Override
	public void run() {
		while (countDown-- > 0) {
			System.out.println(status());
//			Thread.yield();
			try {
				TimeUnit.MILLISECONDS.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	public String status() {
		return "#" + id + "(" + (countDown > 0 ? countDown : "Liftoff!") + "),";
	}
}

主方法的类

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class MailThread {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		// LiftOff lauch =new LiftOff();
		// lauch.run();
		 for(int i =0 ;i<5;i++)
		 {
		 new Thread(new LiftOff()).start();
		 System.out.println("waiting for LiftOff");
		 }

//		ExecutorService exec = Executors.newCachedThreadPool();
//		ExecutorService exec = Executors.newFixedThreadPool(5);
//		ExecutorService exec = Executors.newSingleThreadExecutor();
//		for (int i = 0; i < 5; i++)
//			exec.execute(new LiftOff());
//		exec.shutdown();
	}

}

线程中使用sleep和yield 产生了两种不一样的效果

使用sleep打印结果如下

waiting for LiftOff
waiting for LiftOff
waiting for LiftOff
#0(9),
waiting for LiftOff
waiting for LiftOff
#1(9),
#3(9),
#2(9),
#4(9),
#2(8),
#4(8),
#3(8),
#1(8),
#0(8),
#2(7),
#4(7),
#3(7),
#0(7),
#1(7),
#3(6),
#1(6),
#4(6),
#0(6),
#2(6),
#3(5),
#2(5),
#1(5),
#0(5),
#4(5),
#2(4),
#1(4),
#0(4),
#3(4),
#4(4),
#2(3),
#0(3),
#4(3),
#1(3),
#3(3),
#2(2),
#0(2),
#4(2),
#1(2),
#3(2),
#3(1),
#1(1),
#4(1),
#0(1),
#2(1),
#3(Liftoff!),
#2(Liftoff!),
#0(Liftoff!),
#1(Liftoff!),
#4(Liftoff!),
而使用yield 产生的结果如下

waiting for LiftOff
waiting for LiftOff
waiting for LiftOff
#0(9),
#2(9),
waiting for LiftOff
#0(8),
#2(8),
waiting for LiftOff
#0(7),
#4(9),
#2(7),
#0(6),
#4(8),
#2(6),
#0(5),
#4(7),
#2(5),
#0(4),
#4(6),
#2(4),
#0(3),
#4(5),
#2(3),
#0(2),
#4(4),
#2(2),
#0(1),
#4(3),
#2(1),
#0(Liftoff!),
#4(2),
#2(Liftoff!),
#4(1),
#1(9),
#4(Liftoff!),
#3(9),
#1(8),
#3(8),
#1(7),
#3(7),
#1(6),
#3(6),
#1(5),
#3(5),
#1(4),
#3(4),
#1(3),
#3(3),
#1(2),
#3(2),
#1(1),
#3(1),
#1(Liftoff!),
#3(Liftoff!),

1)     sleep()使当前线程进入停滞状态,所以执行sleep()的线程在指定的时间内肯定不会执行;yield()只是使当前线程重新回到可执行状态,所以执行yield()的线程有可能在进入到可执行状态后马上又被执行。
2)     sleep()可使优先级低的线程得到执行的机会,当然也可以让同优先级和高优先级的线程有执行的机会;yield()只能使同优先级的线程有执行的机会。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值