您的位置:首页 > 其它

(17)21.2.8 并发 练习 8

2012-11-13 12:47 176 查看
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
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: