Java并发编程实例--7.守护(Damon)线程

Java有一种特殊线程叫守护(后台)线程。


1.这类线程拥有非常低的优先级且通常只是在没有其他线程运行的情况下执行。

2.其通常作为无线循环服务去执行某项任务。

3.不能让他们去执行重要任务因为你不知道他们什么时候获得CPU时间或者何时运行结束。

4.一个很典型的案例就是Java的垃圾收集器。



本例中,我们将学习如何去差U你感觉一个守护线程。

为此,我们会开发2个线程;一个用来往队列中写入事件,另一个也就是守护线程用来清理10s之前写入的事件。


 
Event.java
package com.dylan.thread.ch1.c07;

import java.util.Date;

/**
 * 事件类
 * @author xusucheng
 * @create 2018-04-14
 **/
public class Event {
    private Date date;
    private String event;

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getEvent() {
        return event;
    }

    public void setEvent(String event) {
        this.event = event;
    }
}

WriterTask.java

package com.dylan.thread.ch1.c07;

import com.dylan.thread.ch1.c07.Event;

import java.util.Date;
import java.util.Deque;
import java.util.concurrent.TimeUnit;

/**
 * 写事件类
 * @author xusucheng
 * @create 2018-04-14
 **/
public class WriterTask implements Runnable {

    /**
     * Data structure to stores the events
     */
    Deque<Event> deque;

    /**
     * Constructor of the class
     * @param deque data structure that stores the event
     */
    public WriterTask (Deque<Event> deque){
        this.deque=deque;
    }

    /**
     * Main class of the Runnable
     */
    @Override
    public void run() {

        // Writes 100 events
        for (int i=1; i<100; i++) {
            // Creates and initializes the Event objects
            Event event=new Event();
            event.setDate(new Date());
            event.setEvent(String.format("The thread %s has generated an event",Thread.currentThread().getId()));
            // Add to the data structure
            deque.addFirst(event);
            try {
                // Sleeps during one second
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

CleanerTask.java

package com.dylan.thread.ch1.c07;

import java.util.ArrayDeque;
import java.util.Date;
import java.util.Deque;

/**
 * 清理事件类
 *
 * @author xusucheng
 * @create 2018-04-14
 **/
public class CleanerTask extends Thread {

    /**
     * Data structure that stores events
     */
    private Deque<Event> deque;

    /**
     * Constructor of the class
     * @param deque data structure that stores events
     */
    public CleanerTask(Deque<Event> deque) {
        this.deque = deque;
        // Establish that this is a Daemon Thread
        setDaemon(true);
    }


    /**
     * Main method of the class
     */
    @Override
    public void run() {
        while (true) {
            Date date = new Date();
            clean(date);
        }
    }

    /**
     * Method that review the Events data structure and delete
     * the events older than ten seconds
     * @param date
     */
    private void clean(Date date) {
        long difference;
        boolean delete;

        if (deque.size()==0) {
            return;
        }

        delete=false;
        do {
            Event e = deque.getLast();
            difference = date.getTime() - e.getDate().getTime();
            if (difference > 10000) {
                System.out.printf("Cleaner: %s\n",e.getEvent());
                deque.removeLast();
                delete=true;
            }
        } while (difference > 10000);
        if (delete){
            System.out.printf("Cleaner: Size of the queue: %d\n",deque.size());
        }
    }
}

Main.java

package com.dylan.thread.ch1.c07;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author xusucheng
 * @create 2018-04-27
 **/
public class Main {

    /**
     * Main method of the example. Creates three WriterTasks and a CleanerTask
     * @param args
     */
    public static void main(String[] args) {

        // Creates the Event data structure
        Deque<Event> deque=new ArrayDeque<Event>();

        // Creates the three WriterTask and starts them
        WriterTask writer=new WriterTask(deque);
        for (int i=0; i<3; i++){
            Thread thread=new Thread(writer);
            thread.start();
        }

        // Creates a cleaner task and starts them
        CleanerTask cleaner=new CleanerTask(deque);
        cleaner.start();

    }

}


调试输出:

Cleaner: The thread 14 has generated an event
Cleaner: Size of the queue: 30
Cleaner: The thread 13 has generated an event
Cleaner: The thread 15 has generated an event
Cleaner: The thread 15 has generated an event
Cleaner: The thread 14 has generated an event
Cleaner: The thread 13 has generated an event

...
















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值