1,守护线程:生命周期跟main线程一样的~使用场景:做为心跳检查线程,做一些辅助的工作!设置方式:t.setDaemon(true)
2,join方法:子线程先执行完,然后main线程才能执行。注意:多个子线程执行join方法的时候,子线程之间是不受影响的,不会互相阻塞。下面的代码输出结果:
public static void main(String[] args) throws Exception {
Thread t1 = new Thread() {
@Override
public void run() {
for (int i = 0; i < 5; i++)
System.out.println( "====1===" );
}
};
Thread t2 = new Thread() {
@Override
public void run() {
try {
Thread.sleep( 1000 );
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 5; i++)
System.out.println( "====2===" );
}
};
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println( "====main===" );
}
输出:
====1===
====1===
====1===
====1===
====1===
====2===
====2===
====2===
====2===
====2===
====main===
3,线程终止的方法:interrupt()