(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 */
相关文章推荐
- (41)21.4.1 并发 练习 17---Java编程思想之并发笔记
- (16)21.2.8 并发 练习 7
- (18)21.2.8 并发 练习 9
- 练习1-17 编写一个程序,打印长度大于80个字符的所有输入行。
- Python+Selenium练习篇之17-点击复选框-Checkbox
- 蓝桥杯 BASIC-17 基础练习 矩阵乘法
- 机器学习&数据挖掘笔记_17(PGM练习一:贝叶斯网络基本操作)
- 小课堂week17 编程范式巡礼第二季 并发那些事
- C++编程练习(17)----“二叉树非递归遍历的实现“
- 17/7/29小练习
- 算法练习(17):Wildcard Matching
- (33)21.3.3 并发 练习 14
- 剑指offer-算法题练习:part17 反转链表
- 练习17:更多读写练习
- Python 练习实例17
- 17-集合框架-14-常用对象API(集合框架-LinkedList集合-练习(堆栈和队列))
- 基本功练习_2_17_1整形数字转字符串
- C++并发实战17:线程安全的stack和queue
- 构造函数练习(17/09/24)
- 蓝桥杯 BASIC-17 基础练习 矩阵乘法