package com.woyo.test;
/**
* @author antty
* @date:2011-5-27
*
*/
public class ThreadTest {
private static boolean isStop;
public static void main(String[] args) {
startThread();
try {
Thread.sleep(5000);
isStop = true;
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("end===thread");
}
public static void startThread(){
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
startNewThread();
while (true) {
if(isStop){
break;
}
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("=========main thread:" + System.currentTimeMillis());
}
System.out.println("===end");
}
});
thread.start();
}
public static void startNewThread() {
Thread test = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("=========maintest thread:" + System.currentTimeMillis());
}
}
});
//test.setDaemon(true);
test.start();
}
}
daemon Thread 守护线程,Java中可以这样认为:守护主线程(main thread)的线程,与main thread同生共死。默认创建的线程是不是守护线程,要看创建它的线程(父线程)是否守护线程,它与父线程一致。main线程不是守护线程。
所以大部分,我们使用的创建的不是守护线程,想要让它成为守护线程,用thread.setDaemon(true)。这样它就与main同生共死了。main退出的时候,它也终止了(不管是否完成)。
理解有误,其实应该理解为当说有的非守护线程都执行完了,守护线程才终止
thread.setDeamonDaemon(true)---->守护线程