1.
显示如图所示:
以下这个run()不是由单独的线程驱动的,它是在main()中直接调用的,这里依旧是使用了线程,但是总是分配给了main()那个线程,
如图所示:
进行从countDown自减操作:
当countDown为0的时候,也就会去执行Thread.yield()这个方法。
当countDown为-1则结束run()方法:
执行结束之后如下:
完整代码如下所示:
public class LiftOff implements Runnable{
protected int CountDown =10;
private static int taskcount=0;
private final int id=taskcount++;
public LiftOff(){}
public LiftOff(int CountDown){
this.CountDown=CountDown;
}
public String status(){
return "#"+id+"("+(CountDown>0?CountDown:"liftOff!")+")";
}
public void run(){
while (CountDown-->0){//将CountDown进行自减操作:
System.out.println(status());
Thread.yield();
}
}
}