Java Concurrency Programming Example (10): Thread Group _java

Source: Internet
Author: User
Tags thread class

Grouping threads is an interesting feature provided by the Java Concurrency API. We can look at a set of threads as a self-contained unit, and we can manipulate the thread objects in the thread group at will. For example, you can control a set of threads to run the same task without caring how many are still running, and you can use an interrupt call to interrupt the execution of all threads.

Java provides a Threadgroup class to control a thread group. A thread group can be created by thread objects or created by other lines Cheng, generating a tree-structured thread.

The use of Threadgroup is no longer recommended, according to the effective Java instructions. Recommended use of executor.

--D is hereby stated.

In this section, we use Threadgroup to develop a simple example. We will create 10 threads (such as analog search) that are not in hibernation time, and interrupt the remaining threads when one completes.

Know it

Complete the sample code as shown in the following steps.

1. Create a class named result that stores the first name of the thread that completed the task. Declares a string-type private variable, name, and generates the Setter/getter method at the same time. The code is as follows:

Copy Code code as follows:

public class Result {
private String name;

Public String GetName () {
return name;
}

public void SetName (String name) {
THIS.name = name;
}
}

2. Create a class named Searchtask and implement the Runnable interface. The code is as follows:

Copy Code code as follows:

public class Searchtask implements Runnable {

3. Declare a private variable of the result type and instantiate the variable by using the constructor. The code is as follows:

Copy Code code as follows:

private result result;

Public Searchtask (Result result) {
This.result = result;
}

4. Implement the Run () method, in which the Dotask () method is invoked to wait for completion or to be interrupted. The method also prints information to the console to show the start, end, or interruption of the thread. The code is as follows:

Copy Code code as follows:

@Override
public void Run () {
String name = Thread.CurrentThread (). GetName ();
System.out.printf ("Thread%s:start\n", name);
try {
Dotask ();
Result.setname (name);
catch (Interruptedexception e) {
System.out.printf ("Thread%s:interrupted\n", name);
Return
}
System.out.printf ("Thread%s:end\n", name);
}

5. Implement the Dotask () method, which creates a random object and then uses that object to generate a random number to adjust the time that the thread sleeps. The code is as follows:

Copy Code code as follows:

Analog Search
private void Dotask () throws Interruptedexception {
Random Random = new Random (new Date (). GetTime ());
int value = (int) (random.nextdouble () * 100);
System.out.printf ("Thread%s:%d\n",
Thread.CurrentThread (). GetName (), value);
TimeUnit.SECONDS.sleep (value);
}

6. Create the main class of the sample program, Main, and implement the main () method. The code is as follows:

Copy Code code as follows:

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

7. Create a Threadgroup object called Searcher. The code is as follows:

Copy Code code as follows:

Threadgroup Threadgroup = new Threadgroup ("Searcher");

8. Then, create a result object and a Searchtask object. The code is as follows:

Copy Code code as follows:

result is = new result ();
Searchtask searchtask = new Searchtask (result);

The 9.SearchTask object passes the Threadgroup object as the first argument to the thread class constructor when the thread object is created using the creation of 10 thread objects. The code is as follows:
Copy Code code as follows:

for (int i = 0; i < 5; i++) {
Thread thread = new Thread (Threadgroup, searchtask);
Thread.Start ();
try {
TimeUnit.SECONDS.sleep (1);
catch (Interruptedexception e) {
E.printstacktrace ();
}
}

10. Use the list () method to print the information of the Threadgroup object. The code is as follows:

Copy Code code as follows:

System.out.printf ("Number of Threads:%d\n", Threadgroup.activecount ());
SYSTEM.OUT.PRINTLN ("Information about the Thread Group");
Threadgroup.list ();

11. Use Activecount () and enumerate () to get the number of active threads in the Threadgroup object and copy it into a thread array. Use the get* () method to get the name and state of the thread. The code is as follows:

Copy Code code as follows:

thread[] Threads = new Thread[threadgroup.activecount ()];
Threadgroup.enumerate (threads);
for (int i = 0; i < Threadgroup.activecount (); i++) {
System.out.printf ("Thread%s:%s\n", Threads[i].getname (),
Threads[i].getstate ());
}

12. Call the Waitfinish () method and wait for one of the threads in the Threadgroup object to complete the task. Implement this method later. The code is as follows:

Copy Code code as follows:

Waitfinish (Threadgroup);

13. Using the interrupt () method, the other threads in the thread group. The code is as follows:

Copy Code code as follows:

Threadgroup.interrupt ();

14. Implement the Waitfinish () method and use the Activecount () method to control the execution result of the thread. The code is as follows:

Copy Code code as follows:

Wait for the task to complete
private static void Waitfinish (Threadgroup threadgroup) {
while (Threadgroup.activecount () > 9) {
try {
TimeUnit.SECONDS.sleep (1);
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}

15. Run the program to see the execution effect.

Know the reason why

The following is the result of program execution. You will see the output of the list () method, the state of each thread, and so on.

Copy Code code as follows:

Thread Thread-0: Start
Thread Thread-0:52
Thread Thread-1: Start
Thread Thread-1:41
Thread Thread-2: Start
Thread Thread-2:69
Thread Thread-3: Start
Thread Thread-3:60
Thread Thread-4: Start
Thread Thread-4:88
Number of Threads:5
Information about the Thread Group
JAVA.LANG.THREADGROUP[NAME=SEARCHER,MAXPRI=10]
Thread[thread-0,5,searcher]
Thread[thread-1,5,searcher]
Thread[thread-2,5,searcher]
Thread[thread-3,5,searcher]
Thread[thread-4,5,searcher]
Thread Thread-0: timed_waiting
Thread Thread-1: timed_waiting
Thread Thread-2: timed_waiting
Thread Thread-3: timed_waiting
Thread Thread-4: timed_waiting
Thread Thread-1: Interrupted
Thread Thread-4: Interrupted
Thread Thread-2: Interrupted
Thread Thread-0: Interrupted
Thread Thread-3: Interrupted

The Threadgroup class holds numerous thread objects and associated Threadgroup objects. You can access the thread's information by calling the method of the class, and you can perform various operations on it, such as interrupts.

Endless

There are many other ways to Threadgroup class. Please browse through the API documentation for a complete description of the method.

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 following is a full version of the code used in the example in this section.

Complete code for the result class:

Copy Code code as follows:

Package com.diguage.books.concurrencycookbook.chapter1.recipe10;

/**
* Store Query Results
* date:2013-09-30
* time:00:45
*/
public class Result {
private String name;

Public String GetName () {
return name;
}

public void SetName (String name) {
THIS.name = name;
}
}


Complete code for the Searchtask class
Copy Code code as follows:

Package com.diguage.books.concurrencycookbook.chapter1.recipe10;

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

/**
* Analog Search class
* date:2013-10-02
* time:22:38
*/
public class Searchtask implements Runnable {
private result result;

Public Searchtask (Result result) {
This.result = result;
}

    @Override
    public void Run () {
         String name = Thread.CurrentThread (). GetName ();
        System.out.printf ("Thread%s:start\n", name);
        try {
             Dotask ();
            result.setname (name);
       } catch (Interruptedexception e) {
             System.out.printf ("Thread%s:interrupted\n", name);
            return;
       }
        System.out.printf ("Thread%s:end\n", name);
   }

Analog Search
private void Dotask () throws Interruptedexception {
Random Random = new Random (new Date (). GetTime ());
int value = (int) (random.nextdouble () * 100);
System.out.printf ("Thread%s:%d\n",
Thread.CurrentThread (). GetName (), value);
TimeUnit.SECONDS.sleep (value);
}
}

The complete code for the main class:

Copy Code code as follows:

Package com.diguage.books.concurrencycookbook.chapter1.recipe10;

Import Java.util.concurrent.TimeUnit;

/**
* Thread Group Sample main class
* date:2013-10-02
* time:22:45
*/
public class Main {
public static void Main (string[] args) {
Threadgroup Threadgroup = new Threadgroup ("Searcher");

result is = new result ();
Searchtask searchtask = new Searchtask (result);

        for (int i = 0; i < 5; i++) {
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&N bsp;     thread thread = new Thread (Threadgroup, searchtask);
            Thread.Start ();
            try {
                 TimeUnit.SECONDS.sleep (1);
           } catch (Interruptedexception e) {
                 E.printstacktrace ();
           }
       }

System.out.printf ("Number of Threads:%d\n", Threadgroup.activecount ());
SYSTEM.OUT.PRINTLN ("Information about the Thread Group");
Threadgroup.list ();

thread[] Threads = new Thread[threadgroup.activecount ()];
Threadgroup.enumerate (threads);
for (int i = 0; i < Threadgroup.activecount (); i++) {
System.out.printf ("Thread%s:%s\n", Threads[i].getname (),
Threads[i].getstate ());
}

Waitfinish (Threadgroup);

Threadgroup.interrupt ();
}

Wait for the task to complete
private static void Waitfinish (Threadgroup threadgroup) {
while (Threadgroup.activecount () > 9) {
try {
TimeUnit.SECONDS.sleep (1);
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
}


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.