Grouping of threads

Source: Internet
Author: User

The Java Concurrency API provides an interesting feature that can group threads. This allows us to treat a group of threads as a single unit, accessing and manipulating the group's inline objects. For example, for some threads that perform the same tasks, you want to control them, no matter how many threads are running, only one single call is required, and all of these threads will be interrupted.

Java provides a Threadgroup class that represents a set of threads. A thread group can contain thread objects, or it can contain other thread group objects, which are a tree-shaped structure.

In the following example, create 5 threads and have them hibernate for a random time (such as simulating a query), and when one of the threads looks successful, we will break the other 4 threads.

package concurrency;import java.util.date;import java.util.random;import  Java.util.concurrent.timeunit;public class main5 {    public static  void main (String[] args)  {        // Create a thread group object that is identified as searcher         ThreadGroup threadGroup =  New threadgroup ("Searcher");         result result =  new result ();         searchtask searchtask =  new searchtask (result);         for (int i=0;i<5;i++) {            //Each parameter is a Threadgroup object, The second parameter is a Searchtask object             thread thread  = new thread (threadgroup,searchtask);   &nbsP;         thread.start ();             try {                 timeunit.seconds.sleep (1);             } catch  (interruptedexception e)  {                 e.printstacktrace ();             }        }         system.out.printf ("number of threads:  %d\n",  Threadgroup.activecount ());         system.out.printf ("Infomation  About the thread group\n ");         //via list () Method prints the information for the thread group object &NBSP;&NBSP;&NBSP;&NBsp;    threadgroup.list ();         //activecount () Method gets the number of threads that the thread group contains         Thread[] threads = new  Thread[threadgroup.activecount ()];        //through enumerate () Method gets the list of threads that the thread group contains         threadgroup.enumerate (threads);         for (Int i=0;i<threadgroup.activecount (); i++) {             system.out.printf ("thread  %s:  %s\n ",                 threads[i]. GetName (), Threads[i].getstate ());        }         //wait until the first thread of the thread group runs the end ...         waitfinish ( Threadgroup);     &nbsp   //Use the interrupt () method to break the remaining threads in this group          Threadgroup.interrupt ();    }    private static void  Waitfinish (Threadgroup threadgroup) {        while ( Threadgroup.activecount ()  > 4) {             try {                 timeunit.seconds.sleep (1);             }  catch  (exception e)  {                 e.printstacktrace ();             }        }    }}class result{     private string name;&nbSp;   public string getname ()  {         Return name;    }    public void setname (String  Name)  {        this.name = name;     }}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);     }    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);     }}

Note: the list () method prints the state of each thread object. The Threadgroup class has many ways to find JAVA-API documents.

Grouping of threads

Related Article

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.