专注于互联网--专注于架构

最新标签
网站地图
文章索引
Rss订阅

首页 »博文摘选 » 面向对象编程:《Java面向对象编程》学习笔记11——后台线程 »正文

面向对象编程:《Java面向对象编程》学习笔记11——后台线程

来源: 发布时间:星期六, 2009年10月3日 浏览:0次 评论:0
转载自:http://blog.csdn.net/gnuhpc/archive/2009/10/03/4630399.aspx

概念类似于Linux的后台守护进程,JVM的垃圾回收线程就是典型的后台线程,它负责回收其他线程不再使用的内存。只有前台的所有线程结束后后台线程才会结束。main线程默认为前台线程,而由前台线程创建的线程都是前台线程(后台创建的则是后台线程)。

Thread类的setDaemon()方法设置后台线程(线程启动之前),isDaemon()方法判断后台线程。

下边的实例程序我们在主线程中一直将a加1,start方法中创建了一个匿名线程类,它的实例为后台实例,每隔10ms把a重置为0

package org.bupt.test;

public class Machine extends Thread{

    private int a;
    private static int count;
    public void start(){
        super.start();
        Thread daemon = new Thread(){//创建匿名类的实例
            public void run() {
                while (true) {//尽管是无限循环,但是在主线程结束时也会结束。
                    reset();
                    try {
                        sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            private void reset() {
                a=0;
            }
        };
        daemon.setDaemon(true);
        daemon.start();
    }
    public void run() {
        while (true) {
            System.out.println(currentThread().getName()+":"+a++);
            if (count++==100) {
                break;
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Machine machine=new Machine();
        machine.setName("m1");
        machine.start();
    }

}

0

相关文章

读者评论

发表评论

  • 昵称:
  • 内容: