Java has a special kind of thread called daemon thread.
The daemon threads have very low priority.
Normally they only run when no other thread of the same program is running.
When daemon threads are the only threads running in a program, the JVM ends the program finishing these threads.
A typical example of these kind of threads is the Java garbage collector.
We only can call the setDaemon()
method before you call the start()
method.
Once the thread is running, you can't modify its daemon status.
We can use the isDaemon()
method to check if a thread is a daemon thread or a user thread.
import java.util.ArrayDeque; import java.util.Date; import java.util.Deque; import java.util.concurrent.TimeUnit; public class Main { 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();//from w w w . java 2 s. co m } // Creates a cleaner task and starts them CleanerTask cleaner = new CleanerTask(deque); cleaner.start(); } } 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; } } class CleanerTask extends Thread { private Deque<Event> deque; public CleanerTask(Deque<Event> deque) { this.deque = deque; // Establish that this is a Daemon Thread setDaemon(true); } @Override public void run() { while (true) { Date date = new Date(); clean(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()); } } } class WriterTask implements Runnable { private Deque<Event> deque; public WriterTask(Deque<Event> deque) { this.deque = deque; } @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(); } } } }