標籤:中斷線程 守護線程
守護線程
/* * 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++); } }}
JAVA學習筆記(四十)- 守護線程與中斷線程