/*
* Daemon线程,即守护线程
* 一般都在后台运行,为其他线程提供服务,不能单独存在
*/
public class Test08 {
public static void main(String[] args) {
MyThread8 t1 = new MyThread8("守护线程");
System.out.println("是守护线程吗?"+t1.isDaemon());
t1.setDaemon(true);
System.out.println("是守护线程吗?"+t1.isDaemon());
t1.start();
new MyThread8("rubbish");
for (int i = 1; i <= 100; i++) {
System.out.println(Thread.currentThread().getName() + "****" + i);
}
}
}
class MyThread8 extends Thread {
public MyThread8(String name) {
super(name);
setDaemon(true);
start();
}
@Override
public void run() {
while (true) {
System.out.println(Thread.currentThread().getName() + "正在进行垃圾回收!");
}
}
}
/*
* interrupt()中断线程
*/
public class Test09 {
public static void main(String[] args) {
MyThread9 mt = new MyThread9();
Thread thread = new Thread(mt, "first");
thread.start();
for(int i=1;i<=20;i++){
System.out.println(Thread.currentThread().getName() + "***");
}
try {
Thread.sleep(3000);//主线程入睡3秒
} catch (InterruptedException e) {
e.printStackTrace();
}
//中断线程一的休眠
thread.interrupt();
}
}
class MyThread9 implements Runnable {
int num = 1;
@Override
public void run() {
while (true) {
if(num==10){
try {
System.out.println(Thread.currentThread().getName()+"线程即将入睡10秒");
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("我会捶醒了。。。。");
//e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "***" + num++);
}
}
}
原文地址:http://blog.csdn.net/wangzi11322/article/details/44724643