Java中有一种特殊的线程叫做守护(Daemon)线程。这种线程的优先级很低,通常来说,当同一个应用程序里没有其他的线程运作的时候,守护线程才运行。当守护线程是程序中唯一的线程时,守护线程执行结束后,JVM也就结束了这个程序。一个典型的守护线程是Java的垃圾回收器(Garbage Collector)。
示例程序如下:
1.创建Event类
import java.util.Date; 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; } }
2. 创建WriterTask类
import java.util.Date; import java.util.Deque; import java.util.concurrent.TimeUnit; public class WriterTask implements Runnable { private Deque<Event> deque; public WriterTask(Deque<Event> deque){ this.deque = deque; } @Override public void run() { for (int i = 0; i < 100; i++) { Event event = new Event(); event.setDate(new Date()); event.setEvent(String.format( "The thread %s has been generated an event", Thread .currentThread().getId())); deque.addFirst(event); // System.out.println("event: "+event.getDate()); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
3. 创建CleanerTask类
import java.util.Date; import java.util.Deque; import java.util.concurrent.TimeUnit; public class CleanerTask extends Thread { private Deque<Event> deque; public CleanerTask(Deque<Event> deque){ this.deque = deque; this.setDaemon(true); } @Override public void run() { while(true){ Date date = new Date(); clean(date); } } private void clean(Date date){ long diff; boolean delete; if(deque.isEmpty()) return; delete = false; do{ Event e = deque.getLast(); diff = date.getTime()-e.getDate().getTime(); if(diff>10000){ System.out.printf("Cleaner: %s\n", e.getEvent()); deque.removeLast(); delete = true; } }while(diff>10000&&!deque.isEmpty()); if(delete){ System.out.printf("Cleaner: Size of the queue: %d\n", deque.size()); } } }
4. 实现主类Main
import java.util.ArrayDeque; import java.util.Deque; public class Main { public static void main(String[] args) { Deque<Event> deque = new ArrayDeque<Event>(); WriterTask wt = new WriterTask(deque); //创建三个客户端进程 for(int i=0;i<3;i++){ Thread t = new Thread(wt); t.start(); } //创建一个守护进程 CleanerTask ct = new CleanerTask(deque); ct.start(); } }
注:setDaemon()方法只能在start()方法被调用之前设置。一旦程序开始运行,将不能在修改守护状态。
时间: 2024-12-24 21:09:50