Multi-thread synchronization-Case Study of the master thread waiting for completion of all sub-threads

Source: Internet
Author: User

Sometimes we encounter this problem: doing a big task can be broken down into a series of similar small tasks, and a small task is nothing more than the possible differences in parameters!

At this time, if we do not use a thread, we will inevitably waste a lot of time to complete the entire big thing, and the use of the thread will have such a problem:

After the main thread starts all sub-threads for concurrent execution, the main thread will return directly, resulting in the completion of the external function interpretation of the entire big thing, but it is not actually completed!

In view of the above situation, I think I will adopt multi-threaded execution and solve the problem that the main thread waits for the sub-thread.

Here I use Java for case analysis. <喎?http: kf ware vc " target="_blank" class="keylink"> VcD4KPHA + ytfPyL2owaLSu7j2z9 + release/L + release/nT0NfTz9 + release/7 usRDVVDNrMqxz/u6xMqxvOSjrMirsr/release/resume = "brush: java; "> public class ThreadManager implements policyinterface {private final Object mLock = new Object (); private int mCount = 0; private 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. policyall ();}}}
This class is integrated from: NotifyInterface interface. yyinterface is used to notify the main thread that the job has been completed by the sub-thread. When ThreadManager is instantiated, an int value is passed in to set the number of sub-threads to be started, of course, this method is used for a brief introduction. The actual situation may be more complicated.

The constructor enters the constructor method after instantiation. The constructor thread starts and enters the loop wait state. When all sub-threads are detected to be completed, the loop is exited. If not, the constructor enters the critical waiting state, the critical value will be notified once when the main thread is notified through the interface, and the loop will be executed once. If the exit condition is not met, the critical value will continue to be waited. Until it is met.

The policyinterface interface is as follows:

public interface NotifyInterface {public abstract void runEnd();}

The sub-thread ThreadDoThing. java used for testing is as follows:

public class ThreadDoThing extends Thread {private NotifyInterface mInterface = null;private int mId = 0;private String mArgs = 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 is:" + this.mArgs);System.out.println(this.mId + ":Doing...");int sleepTime = (int) (Math.random() * 1000);try {Thread.sleep(sleepTime);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(this.mId + ":SleepTime is:" + sleepTime);this.notifyEnd();System.out.println(this.mId + ":Do End.");}private void notifyEnd() {if (this.mInterface != null)this.mInterface.runEnd();System.out.println(this.mId + ":Notify End.");}}

This class is inherited from the Thread class. You can directly override the Run () method to complete the work!

In my work, I used a random sleep within 1 s to replace the time of my work. After that, the interface call notification was completed.

The test method is as follows:

/** * @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 complicated, and even more sub-threads exist under the sub-thread!

You can consider the specific situation, check whether all the results are returned, there are multiple ways or even set to add a timer and so on.

You will have time to draw a detailed graph later!

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: 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.