(17)21.2.8 并发 练习 8

package jiangning.c21;

import java.util.concurrent.TimeUnit;
/**
 * Java编程思想 第四版 c21 并发 练习8:把SimpleThread.java中的所有现场修改成后台线程,并验证一旦main()退出,程序立刻终止。
 *
 * @author JiangNing
 *
 */
public class SimpleThread extends Thread{
        private int countDown = 5;
      private static int threadCount = 0;
      public SimpleThread(){
           super(Integer.toString(++ threadCount));
           start();
     }
      public String toString(){
            return "#" + getName() + "(" + countDown + ")" ;
     }
      public void run(){
            while(true ){
                 System. out.println(this);
                  if(countDown --==0){
                        return;
                 }
           }
     }
      public static void main(String[] args) throws Exception{
            for(int i=0; i<5; i++){
                  new SimpleThread().setDaemon(true);
           }
            TimeUnit. MILLISECONDS.sleep(100);
     }
}

/**
 * 出现这样的异常是因为在任务启动之后才进行设置为后台线程。
 *
#1(5)
#1(4)
#1(3)
#1(2)
#1(1)
#1(0)
Exception in thread "main" java. lang.IllegalThreadStateException
       at java.lang .Thread.setDaemon(Thread.java:1232)
       at jiangning.c21.SimpleThread.main(SimpleThread.java:26)
*/


package jiangning.c21;

public class Exercise8 extends Thread{
        private int countDown = 5;
      private static int threadCount = 0;
      public Exercise8(){
           super(Integer.toString(++ threadCount));
           this.setDaemon(true);
           start();
     }
      public String toString(){
            return "#" + getName() + "(" + countDown + ")" ;
     }
      public void run(){
            while(true ){
                 System. out.println(this + ":  "+ this.isDaemon());
                  if(countDown --==0){
                        return;
                 }
           }
     }
      public static void main(String[] args) throws Exception{
        System. out.println("over end" );
            for(int i=0; i<5; i++){
                   new Exercise8();
           }
     }
}

/**
 * over end
#2(5):  true
#2(4):  true
#2(3):  true
#2(2):  true
#2(1):  true
#1(5):  true
#1(4):  true
#1(3):  true
#1(2):  true
#1(1):  true
#1(0):  true
#3(5):  true
#4(5):  true
#4(4):  true
#5(5):  true
#5(4):  true
#2(0):  true
#5(3):  true
#4(3):  true
#3(4):  true
#3(3):  true
#3(2):  true
#4(2):  true
#4(1):  true
#4(0):  true
#5(2):  true
#3(1):  true
#5(1):  true
#5(0):  true
#3(0):  true
*/

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值