Java concurrent programming example of seven: creation and execution of daemon threads

  • 2020-04-01 03:33:09
  • OfStack

Java has a special thread, the daemon thread, which has a very low priority and only executes when other threads in the same program are not executing.

Because daemon threads have these features, they are typically used to service regular threads (also known as user threads) in a program. They typically have an infinite loop, either waiting for a request to be served, or performing a task, etc. They can't do any important work, because we're not sure when they're going to allocate CPU run time, and they terminate automatically when no other threads execute. A typical use of such threads is Java garbage collection.

In the example in this section, we will create two threads, one a normal thread, to write events to the queue; The other is the daemon thread, which clears events from the queue and removes events that have been around for more than 10 seconds.

learning

Follow these steps to implement the sample program.

1. Create the Event class, which is only used to hold the Event information needed for program execution. Declaration of two properties, one is Java. Util.Date type of Date familiar, the other is String type of event property; The read-write methods for both properties are then generated. The code is as follows:


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. Create a class called WriterTask and implement the Runnable interface. The code is as follows:


public class WriterTask implements Runnable {

Declare a queue property to store events, implement the constructor of the class, and initialize the queue property with its arguments. The code is as follows:


private Deque<Event> deque; public WriterTask(Deque<Event> deque) {
    this.deque = deque;
}

4. Implement the run() method for the task, which contains a loop that is traversed 100 times. In each iteration, create a new Event object, save it to the queue, and sleep for another second. The code is as follows:


@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 generated an event",
                Thread.currentThread().getId()));
        deque.addFirst(event);
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

5. Create a class called CleanerTask and inherit from the Thread class. The code is as follows:


public class CleanerTask extends Thread {

Declare a queue property to store events, implement the constructor of the class, and initialize the queue property with its arguments. In the constructor, the thread is set to the daemon thread by calling the setDaemon() method. The code is as follows:


private Deque<Event> deque; public CleanerTask(Deque<Event> deque) {
    this.deque = deque;
    setDaemon(true);
}

7. Implement the run() method, which has an infinite loop inside it to get the current time, and then call the clearn() method. The code is as follows:


@Override
public void run() {
    while (true) {
        Date date = new Date();
        clean(date);
    }
}

8. Implement the clean() method, in which you get the last time, then check the time difference between the time and the current time, delete the current event if it was created 10 seconds ago, and check the next event. If an event is deleted, the information that the deleted event is printed is displayed, and the latest length of the queue is also printed, so that the progress of the program can be observed. The code is as follows:


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: %sn", e.getDate());
            deque.removeLast();
            delete = true;
        }
    } while (difference > 10000);     if (delete) {
        System.out.printf("Clearner: Size of the queue: %dn", deque.size());
    }
}

9. Create the Main class of the program, the Main class, and then implement the Main () method. The code is as follows:


public class Main {
    public static void main(String[] args) {

10. Use the Deque class to create a queue to store events. The code is as follows:


Deque<Event> deque = new ArrayDeque<>();

11. Create and start three WriterTask threads and one CleanerTask thread. The code is as follows:


Deque<Event> deque = new ArrayDeque<>();
WriterTask writer = new WriterTask(deque);
for (int i = 0; i < 3; i++) {
    Thread thread = new Thread(writer);
    thread.start();
} CleanerTask cleaner = new CleanerTask(deque);
cleaner.start();

12. Execute the program and view the results.

Know why

The result of analyzing the execution of the program is that the queue increases to 30 and then changes between 27 and 30 until the program is finished.

The program starts with three WriterTask threads, each adding an event to the queue, and then sleeps for 1 second. After the first 10 seconds, there will be 30 events in the queue. During this 10-second period, when all three WriterTask threads are asleep, the CleanerTask thread will also run, but no events will be deleted, as all events are less than 10 seconds old. Three writertasks are added to the queue every second after the first 10 seconds; Similarly, CleanerTask removes three events per second. So the number of events hovers between 27 and 30.

When all WriterTask threads are asleep, we are free to process the time that allows the daemon thread to run. If you set the sleep time for the WriterTask thread to be shorter, the CleanerTask thread will get less CPU run time. If so, because the CleanerTask thread never gets enough run time to remove enough events, the length of the queue will continue to grow.

endless

You can only set a thread as a daemon thread by calling the setDaemon() method before calling the start() method. Once a thread starts running, you cannot modify the daemon state.

You can also use isDaemon() to check if a thread is a daemon thread. Returns true if it is a daemon thread. Returns false for a normal thread.

si

This article is a translation from the Java7 Concurrency Cookbook (D jago to Java7 Concurrency examples) and is intended for use only as a learning material. Not to be used in any commercial activities without authorization.

Small has becomes

A complete version of all the sample code used in this section.

The complete code for the Event class


package com.diguage.books.concurrencycookbook.chapter1.recipe7; import java.util.Date; /**
 * Event information class
 * Date: 2013-09-19
 * Time: 22:56
 */
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;
    }
}

Complete code for the WriterTask class


package com.diguage.books.concurrencycookbook.chapter1.recipe7; import java.util.Date;
import java.util.Deque;
import java.util.concurrent.TimeUnit; /**
 * One event per second is generated.
 * Date: 2013-09-19
 * Time: 22:59
 */
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 generated an event",
                    Thread.currentThread().getId()));
            deque.addFirst(event);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Complete code for the CleanerTask class


package com.diguage.books.concurrencycookbook.chapter1.recipe7; import java.util.Date;
import java.util.Deque; /**
 * Event cleaning
 * Date: 2013-09-19
 * Time: 23:33
 */
public class CleanerTask extends Thread {
    private Deque<Event> deque;     public CleanerTask(Deque<Event> deque) {
        this.deque = deque;
        setDaemon(true);
    }     @Override
    public void run() {
        while (true) {
            Date date = new Date();
            clean(date);
        }
    }     /**
     * Delete events.
     *
     * @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: %sn", e.getDate());
                deque.removeLast();
                delete = true;
            }
        } while (difference > 10000);         if (delete) {
            System.out.printf("Clearner: Size of the queue: %dn", deque.size());
        }
    }
}

The complete code for the Main class


package com.diguage.books.concurrencycookbook.chapter1.recipe7; import java.util.ArrayDeque;
import java.util.Deque; /**
 * Date: 2013-09-19
 * Time: 23:54
 */
public class Main {
    public static void main(String[] args) {
        Deque<Event> deque = new ArrayDeque<>();
        WriterTask writer = new WriterTask(deque);
        for (int i = 0; i < 3; i++) {
            Thread thread = new Thread(writer);
            thread.start();
        }         CleanerTask cleaner = new CleanerTask(deque);
        cleaner.start();
    }
}


Related articles: