Java Concurrency Programming Example (vii): Daemon thread creation and running _java

Source: Internet
Author: User
Tags current time garbage collection getdate thread class

Java has a special thread, the daemon thread, which is particularly low in priority and executes only if other threads in the same program do not execute.

Because the daemon has these attributes, it is generally used to provide services for ordinary threads (also known as user threads) in the program. They typically have an infinite loop, or are used to wait for a request service, or to perform a task. They cannot do any important work because we are unsure of what they can allocate to CPU uptime, and when no other thread executes, they terminate automatically. A typical application of this type of thread is Java garbage collection.

In this example, we will create two threads, one normal thread, write events to the queue, the other a daemon, purge events in the queue, and delete events that are longer than 10 seconds.

Know it

Follow the steps below to implement the sample program.

1. Create the event class, which is used only to save the event information required for program execution. Declares two properties, one is familiar with the java.util.Date type, the other is a string event property, and then the read-write method of the two properties is generated. The code is as follows:

Copy Code code 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 named Writertask and implement the Runnable interface. The code is as follows:

Copy Code code as follows:

public class Writertask implements Runnable {

3. Declare a queue attribute used to store events, implement the constructor of the class, and use its arguments to initialize the queue properties. The code is as follows:

Copy Code code as follows:

Private deque<event> Deque;

Public Writertask (deque<event> Deque) {
This.deque = deque;
}

4. Implement the Run () method of the task, which contains a loop that traverses 100 times. In each traversal, create a new event object and save it in the queue for 1 seconds. The code is as follows:

Copy Code code as follows:

@Override
public void Run () {
for (int i = 0; i < 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 named Cleanertask and inherit the thread class. The code is as follows:

Copy Code code as follows:

public class Cleanertask extends Thread {

6. Declare a queue attribute used to store events, implement the constructor of the class, and use its arguments to initialize the queue properties. In the constructor method, the thread is set to a daemon by calling the Setdaemon () method. The code is as follows:

Copy Code code 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 to get the current time and then call the Clearn () method. The code is as follows:

Copy Code code 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, and then check the time difference between the times and the current time, and if you created it before 10 seconds, delete the current event, and then check the next event. If an event is deleted, display the information that prints out the deleted event, and then print out the queue's latest length, so that you can observe the progress of the program's execution. The code is as follows:

Copy Code code 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:%s\n", e.getdate ());
Deque.removelast ();
Delete = true;
}
while (Difference > 10000);

if (delete) {
System.out.printf ("Clearner:size of the queue:%d\n", deque.size ());
}
}

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

Copy Code code as follows:

public class Main {
public static void Main (string[] args) {

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

Copy Code code as follows:

deque<event> Deque = new arraydeque<> ();

11. Create and start three writertask threads and one cleanertask thread. The code is as follows:

Copy Code code 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 to see the results of the execution.

Know the reason why

The result of the analysis program shows that the queue increases to 30 first, then changes between 27 and 30, knowing that the execution of the program is complete.

The program first executes from three writertask threads, each thread adds an event first, then sleeps for 1 seconds. After the first 10 seconds, there will be 30 events in the queue. During this 10-second period, when three writertask threads are asleep, the cleanertask thread runs, but no events are deleted because all events are not generated for more than 10 seconds. In the first 10 seconds, three writertask per second add three events to the queue, as well as three events per second cleanertask. So the number of events hovers between 27 and 30.

When the Writertask thread sleeps, we are free to process the time, allowing the daemon to run. If you set the Writertask thread to a shorter sleep time, the cleanertask thread gets less CPU uptime. If so, the length of the queue will continue to grow because the cleanertask thread has not been able to get enough running time to remove enough events.

Endless

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

You can also use Isdaemon () to check whether a thread is a daemon thread. Returns true if it is a daemon, or false if it is a normal thread.

Copycat

This article is from the "Java 7 Concurrency Cookbook" (D-Gua to "Java7 concurrent Sample Set") translation, only as learning materials used. No authorization shall be applied to any commercial act.

Small has become

The full version of all the sample code used in this section.

The complete code for the event class

Copy Code code as follows:

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

Copy Code code as follows:

Package Com.diguage.books.concurrencycookbook.chapter1.recipe7;

Import Java.util.Date;
Import Java.util.Deque;
Import Java.util.concurrent.TimeUnit;

/**
* Generate an event per second.
* 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 < 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

Copy Code code as follows:

Package Com.diguage.books.concurrencycookbook.chapter1.recipe7;

Import Java.util.Date;
Import Java.util.Deque;

/**
* Event Cleanup
* 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 event.
*
* @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.getdate ());
                Deque.removelast ();
                Delete = true;
           }
       } while (Difference > 10000);

if (delete) {
System.out.printf ("Clearner:size of the queue:%d\n", deque.size ());
}
}
}

The complete code for the main class

Copy Code code as follows:

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 ();
}
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.