首页 > 编程语言 > 详细

JAVA学习笔记(四十)- 守护线程与中断线程

时间:2015-03-29 10:52:39      阅读:143      评论:0      收藏:0      [点我收藏+]

守护线程

/*
 * 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学习笔记(四十)- 守护线程与中断线程

原文:http://blog.csdn.net/wangzi11322/article/details/44724643

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!