Five Ways to wait (sync) Java threads

Source: Internet
Author: User
Tags thread logic

During the interview, the interviewer often asks, "A thread Cheng a sub-thread, how to make the child thread's business execution complete, and then execute the main thread business logic." For this problem, I can think of there are five ways, detailed please visit the source code

1. Using the Join method with the thread class, add the child thread to the main thread and execute the main thread logic after the child thread finishes executing.

For example

public static void Joindemo ()        throws Interruptedexception    {        System.out.println ("=========test with join= ====");        Joinworker worker1 = new Joinworker ("Worker1");        Joinworker worker2 = new Joinworker ("Worker2");        Worker1.start ();        Worker2.start ();        Worker1.join ();        Worker2.join ();        Dosuperwork ();    }

2, using the Countdownlatch class in the concurrent package of JDK, using Countdownlatch, each thread calls its Countdown method to make counter-1, the main thread calls the await method to block wait, Continues until the Countdownlatch counter is 0 o'clock, for example

First, define the child threads

Static class Countdownlatchworker extends Thread    {        String workername;        Countdownlatch latch;        Public Countdownlatchworker (String workername, countdownlatch latch)        {            this.workername = workername;            This.latch = latch;        }        public void Run ()        {            System.out.println ("Sub-Worker" + Workername + "do-work-begin at"                               + sdf.format (new Da Te ()));            New Threadwaitdemo (). Dosomework ()//Do the actual work            System.out.println ("Sub Worker" + workername + "Do job complete at" 
   + Sdf.format (New Date ()));            Latch.countdown ();//After completion, the counter is reduced by one        }    }

Research await method in main thread blocks wait until all threads complete

public static void Countdownlatchdemo ()        throws Interruptedexception    {        System.out.println ("========= Test with countdownlatch===== ");        Countdownlatch latch = new Countdownlatch (2);        Countdownlatchworker worker1 = new Countdownlatchworker ("Worker1", latch);        Countdownlatchworker worker2 = new Countdownlatchworker ("Worker2", latch);        Worker1.start ();        Worker2.start ();        Main thread blocking wait        latch.await ();        Dosuperwork ();    }

3, using the JDK and contract cyclicbarrier,cyclicbarrier similar to Countdownlatch is also a counter, the difference is that the cyclicbarrier await () method is not called once, the count will be reduced by 1, and blocks the current thread. When the count is reduced to 0 o'clock, the blocking is lifted, and all the blocked threads on this cyclicbarrier begin to run. After that, if the await () method is called again, the Count becomes N-1, and the new round starts again with a runnable parameter, the runnable task after the number of Cyclicbarrier is reached, All other threads are executed before they are awakened.

Examples such as the following

public static void Cyclicbarrierdemo ()        throws Interruptedexception, brokenbarrierexception    {        System.out.println ("=========test with cyclicbarrier=====");        Cyclicbarrier cb = new Cyclicbarrier (2, New Runnable ()        {            //The main thread business is put into the Cyclicbarrier constructor method, all threads are executed            when they reach barrier @SuppressWarnings ("static-access") public            Void Run ()            {                new Threadwaitdemo (). Dosuperwork ();            }        ); /set to wait two threads        executorservice executor = Executors.newfixedthreadpool (2);        Cyclicbarrierworker worker1 = new Cyclicbarrierworker ("Worker1", CB);        Cyclicbarrierworker worker2 = new Cyclicbarrierworker ("Worker2", CB);        Executor.execute (worker1);        Executor.execute (worker2);        Executor.shutdown ();    }

4, using the executors framework of the JDK and the contract, Executorservice of the InvokeAll method to investigate callable collection, batch execution of multiple threads, after the end of the InvokeAll method, and then execute the main thread other business logic

Examples such as the following

public static void Callabledemo () throws Interruptedexception {System.out.println ("=========test with Ca        llable===== ");        list<callable<integer>> calllist = new arraylist<callable<integer>> ();        Executorservice exec = Executors.newfixedthreadpool (2); Implement Calllist.add (New Callable<integer> () {public Integer call () with Anonymous inner class Rows Exception {System.out.println ("Sub Worker worker1 do work begin at" + Sdf.format (new Date                ()));                                   New Threadwaitdemo (). Dosomework ()//Do the actual work System.out.println ("Sub-Worker worker1 do job complete at"                + Sdf.format (new Date ()));            return 0;        }        });            Calllist.add (New callable<integer> () {public Integer call () throws Exception {System.out.println ("Sub Worker worker2 do worK begin at "+ Sdf.format (new Date ()));                                   New Threadwaitdemo (). Dosomework ()//Do the actual work System.out.println ("Sub-Worker worker2 do job complete at"                + Sdf.format (new Date ()));            return 0;        }        });        Exec.invokeall (calllist);        Exec.shutdown ();    Dosuperwork (); }
5, this is too disgusting, simply say the method, the main thread creates a list of threads, saves each child thread to the list, and then periodically polls the list for the sub-thread state, and then executes the main thread logic after all the threads have completed


Five Ways to wait (sync) Java threads

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.