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()只能使同优先级的线程有执行的机会。