[Java] [Android] Multi-threaded synchronization-The main thread waits for all child threads to complete the case

Source: Internet
Author: User

Sometimes we encounter this kind of problem: to do a big thing can be broken down to do a series of similar small things, and the small thing is simply the number of participants may not be the same!

At this point, assuming that the thread is not used, we are bound to waste a lot of time to complete the big thing. The problem with threading would be this:

The main thread starts all of the child threads concurrently running after the main thread returns directly, causing the external function to interpret the whole big thing finished, but actually not finished!


In the light of the above, I think I will take the multi-threaded way to run the same time to resolve the main thread waiting for the child thread.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvcwl1anvlcg==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/southeast ">

Here I use Java for case analysis.

First, create a thread management class. Used to start all child threads and wait for all child threads to complete. Here does not use sleep for a period of time after the cyclic detection of the way (consumption of the same time consumption of CPU time, all completed time is not enough timely and other shortcomings). Instead, a wait threshold is used.

Threadmanager.java such as the following:

public class Threadmanager implements Notifyinterface {Private Final object mLock = new Object ();p rivate int mCount = 0;PR ivate int endcount = 0;public threadmanager (int count) {System.out.println ("Manager in."); This.mcount = Count;this.addthread (); synchronized (MLock) {while (true) {if (Checkend ()) Break;try {mlock.wait ();} catch (Interruptedexception e) {E.printstacktrace ();}}} System.out.println ("Manager out.");} private void Addthread () {System.out.println ("Manager addthread ()."); for (int i = 1; I <= mCount; i++) {threaddothing dthread = new Threaddothing (i, ' T ' + I, this);//Startdthread.start (); }}private Boolean Checkend () {Boolean bflag = False;bflag = Endcount >= mCount; System.out.println ("Manager checkend (). Return is: "+ bflag); return bflag;} @Overridepublic void RunEnd () {synchronized (MLock) {++endcount;mlock.notifyall ();}}}

This class is integrated from: Notifyinterface interface, Notifyinterface is used for child threads to notify the main thread that it has finished working with the class. The Threadmanager is instantiated with an int value that sets the number of child threads to start, which is, of course, for the sake of introduction, and the actual situation may be more complex.

After the instantiation into the construction method, the child thread will be started, after the start of the loop wait, when the detection of all sub-threads to exit the loop, no will enter the critical value waits, until the interface is notified when the main thread is complete will notify the critical value once. The loop will now run once. Assume that the exit condition is not met will continue to wait for the threshold value. Until satisfied.

Notifyinterface interfaces such as the following:

Public interface Notifyinterface {public abstract void runEnd ();}

The tested sub-thread Threaddothing.java such as the following:

public class Threaddothing extends Thread {private Notifyinterface minterface = null;private int mId = 0;private String MA RGS = null;public threaddothing (int id, String args, Notifyinterface iface) {this.mid = Id;this.margs = Args;this. AddInterface (iface);} public void AddInterface (Notifyinterface iface) {this.minterface = Iface;} @Overridepublic void Run () {System.out.println ("threaddothing Id is:" + This.mid + "Args are:" + This.margs); System.out.println (This.mid + ":D oing ..."), int sleeptime = (int) (Math.random () * +); try {thread.sleep (sleeptime);} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println (This.mid + ": Sleeptime is:" + sleeptime); This.notifyend (); System.out.println (This.mid + ":D o End."); private void Notifyend () {if (this.minterface! = null) this.mInterface.runEnd (); System.out.println (This.mid + ": Notify End.");}

This class inherits from the thread class and can directly rewrite the run () method to complete the work.

At work, I used a random 1s sleep to replace the time of the job. After completion of the call interface notification is complete.


Test methods such as the following:

/** * @param args */public static void main (string[] args) {//TODO auto-generated method Stubthreadmanager Manager = new Threadmanager (10);}

Test results:

Manager In.manager Addthread (). Threaddothing ID is:1 args is:t1threaddothing id is:2 args is:T22:Doing ... 1:doing ... Threaddothing ID is:3 args is:t3threaddothing id is:4 args is:T43:Doing ... 4:doing ... Threaddothing Id is:5 Args is:T55:Doing ... Threaddothing Id is:6 Args is:t6manager checkend (). Return is:falsethreaddothing ID is:8 args is:t8threaddothing id is:7 args is:T78:Doing ... Threaddothing Id is:9 Args is:T99:Doing ... 6:doing ... Threaddothing Id is:10 Args is:T107:Doing ... 10:doing ... 3:sleeptime is:1113:notify end.3:do End.manager checkend (). Return is:false5:SleepTime is:1425:notify End.manager checkend (). Return is:false5:Do end.4:sleeptime is:1994:notify end.manager checkend (). Return is:false4:Do end.7:sleeptime is:3427:notify end.manager checkend (). Return is:false7:Do end.10:sleeptime is:34610:notify end.manager checkend (). Return is:false10:Do end.6:sleeptime is:3976:notify end.manager checkend (). Return is:false6:Do end.9:sleeptime is:4689:notify end.manager checkend (). Return Is:false9:do end.1:sleeptime is:4751:notify End.manager checkend (). Return is:false1:Do end.2:sleeptime Is:686manager checkend (). Return is:false2:Notify end.2:do end.8:sleeptime is:8288:notify end.manager checkend (). Return Is:true8:Do End.manager out.

The actual situation may be more complex. There are many other sub-threads even under the sub-thread!

Detailed information can be derived from the consideration of whether all returns can also be set to add a timer and the like in many ways.

Later there is time to draw a specific point of the map!


[Java] [Android] Multi-threaded synchronization-The main thread waits for all child threads to complete the case

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.