2.5 驻守后台:守护线程

package 第二章.守护线程;

/**
* Created by zzq on 2018/1/18.
*/
public class 守护线程Test {
public static class MyThread extends Thread{
private int i = 0;
@Override
public void run(){
super.run();
try{
while(true){
i++;
System.out.println("i="+i);
Thread.sleep(1000);
}
}catch(InterruptedException ie){
ie.printStackTrace();
}
}
}
public static class testThread extends Thread{
@Override
public void run(){
try{
Thread.sleep(10000); //testThread线程约10秒后结束
System.out.println(Thread.currentThread().getName()+"线程结束!");
}catch(InterruptedException ie){
ie.printStackTrace();
}
}
}
public static class T1 extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i);
}
}
}

public static void main(String[] args) throws InterruptedException {
try{
MyThread thread = new MyThread();
thread.setName("thread");
thread.setDaemon(true); //将thread线程设为守护线程
thread.start();
testThread t = new testThread();
t.setName("testThread");
t.start();
t.stop();
Thread.sleep(5000);//main线程在这里停留5秒
System.out.println("主线程结束了");//5秒后main线程结束了,但是testThread线程还在执行,所以守护线程继续工作

/*当所有线程都结束时,thread线程也随之结束*/
}catch(InterruptedException ie){
ie.printStackTrace();
}
/*守护线程 必须在start()方法之前 不然会报错,告诉你设置守护线程失败
public final void setDaemon(boolean on) {
checkAccess();
if (isAlive()) {
throw new IllegalThreadStateException();
}
daemon = on;
}
源码中说明 如果线程的运行状态是true 会抛异常
*/
}
}

转载于:https://www.cnblogs.com/anxbb/p/8425435.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值