本帖最后由 黄湘怡 于 2011-12-26 20:15 编辑
线程中的setDaemon到底有什么用呢?- package cn.thread;
- public class Demo8 {
- /**
- * @param args
- * @throws InterruptedException
- */
- public static void main(String[] args) throws InterruptedException {
- // TODO Auto-generated method stub
- ThTest th = new ThTest();
-
-
- Thread t = new Thread(new Runnable(){
- public void run(){
- for(int x = 0;x<10;x++){
- System.out.println("x = "+x);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- });
-
- for(int m = 0;m<5;m++){
- System.out.println("m = "+m);
- Thread.sleep(1000);
- }
-
- t.setDaemon(true);
- th.setDaemon(true);
- t.start();
- th.start();
-
- }
-
- }
- class ThTest extends Thread{
- public void run(){
- for(int i = 0;i<10;i++){
- System.out.println("i = "+i);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
复制代码 运行的结果是:
m = 0
m = 1
m = 2
m = 3
m = 4
x = 0
i = 0
当for循环结束时,两个线程都都结束了,那写上有什么用呢? |