java中有两种线程,用户线程和守护线程
用户线程:主线程停止时,用户线程不会停止
守护线程:主线程停止时,守护线程也会停止
通过setDaemon(true)方法设置为守护线程
package com.rejoice.concurrency;
/**
* 守护线程:当主线程停止时,子线程自动停止
* @author jiongyi
*
*/
public class DaemonThread {
public static void main(String[] args) throws InterruptedException {
MyThread thread1 = new MyThread();
thread1.setDaemon(true);//设置子线程为守护线程
thread1.start();
Thread.sleep(200);
System.err.println("主线程停止。。。");
}
static class MyThread extends Thread{
@Override
public void run() {
while(true) {
System.err.println("子线程"+Thread.currentThread().getName()+"运行。。。。。");
}
}
}
}
运行结果

网友评论