
注意事项
1.守护线程的设置setDaemon(true)必须先放在start()之前,否则程序会出错。
2.守护线程中创建的所有子线程都是守护线程。
使用jojn()方法,无论线程是用户线程还是守护线程,都会等待一个线程完成。
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread( new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println( "i:" + i + ",isDaemon:" +
Thread.currentThread().isDaemon());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
thread.setDaemon( true );
}
|
以上就是java守护线程的注意事项,希望对大家有所帮助。更多Java学习指路:Java基础
推荐操作环境:windows7系统、java10版,DELL G3电脑。