JAVA學習筆記(四十)- 守護線程與中斷線程

來源:互聯網
上載者:User

標籤:中斷線程   守護線程   

守護線程
/* * 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學習筆記(四十)- 守護線程與中斷線程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.