Java multi-threaded, main thread waits for all child threads to complete, share resources

Source: Internet
Author: User

1.Java Creating and starting threads

Java provides two ways to create and start threads: 1. Direct thread class, 2. Implement the Runable interface.

1.1 Inheriting the Thread class

public class MyThread extends Thread {public void run () {for (int i=0;i<5;i++) {System.out.println (This.getname () + ":" + i);}} public static void Main (string[] args) {//Create 3 threads myThread myThread1 = new MyThread (); MyThread myThread2 = new MyThread (); MyT Hread myThread3 = new MyThread ();//Start thread Mythread1.start (); Mythread2.start (); Mythread3.start ();}}

  

Thread-by-step, random execution

Note that the startup thread must be Thread.Start () and not Thread.run (). Otherwise it is sequential execution, losing the meaning of multithreading.

 Public classMyThreadextendsThread { Public voidrun () { for(inti=0;i<5;i++) {System.out.println ( This. GetName () + ":" +i); }    }         Public Static voidMain (string[] args) {//Create 3 ThreadsMyThread MyThread1 =NewMyThread (); MyThread myThread2=NewMyThread (); MyThread myThread3=NewMyThread (); //Start ThreadMythread1.run ();        Mythread2.run ();    Mythread3.run (); }}

Output: Three threads sequential execution

1.2 Implement Runnable Interface implementation

 Public classMyrunnableImplementsRunnable {PrivateString name;  Public voidrun () { for(inti=0;i<5;i++) {System.out.println ( This. GetName () + ":" +i); }    }     PublicString GetName () {returnname; }     Publicmyrunnable (String name) {Super();  This. Name =name; }             Public Static voidMain (string[] args) {//Create 3 ThreadsMyrunnable MyRunnable1 =NewMyrunnable ("Thread1"); Myrunnable MyRunnable2=NewMyrunnable ("Thread2"); Myrunnable MyRunnable3=NewMyrunnable ("Thread3"); //starting the thread, because there is no Start method in Runnable, you should start the thread by taking your runnable instance as the thread (target target) parameter .//multiple runnable instances, executing the same Code        NewThread (MyRunnable1). Start (); NewThread (MyRunnable2). Start (); NewThread (MyRunnable3). Start (); }}

Execution result: Random execution

2. What's the difference between the two ways, and then look at the following code, using runnable to achieve resource sharing, where the sharing of knowledge part shared

Like the ticketing system.

1  Public classMyThreadextendsThread {2     Private inttickets=5;//Total 5 Tickets3      Public voidrun () {4          for(inti=0;i<10;i++){5             if(tickets>0){6System.out.println ( This. GetName () + ":" +tickets--);7             }8         }9     }Ten      One      Public Static voidMain (string[] args) { A         //Create 3 Threads -MyThread MyThread1 =NewMyThread (); -MyThread myThread2 =NewMyThread (); theMyThread myThread3 =NewMyThread (); -         //Start Thread - Mythread1.start (); - Mythread2.start (); + Mythread3.start (); -     } +}

Output: Each thread sold 5 tickets, equivalent to 15 tickets

Then take a look at using runnable to implement 5 tickets in three process sharing systems

 Public classMyrunnableImplementsRunnable {Private intTickets=5;  Public voidrun () { for(inti=0;i<10;i++){            if(tickets>0) {System.out.println (Thread.CurrentThread (). GetName ()+ "Selling Tickets:" +tickets--); }        }    }         Public Static voidMain (string[] args) {//Create 3 ThreadsMyrunnable MyRunnable1 =Newmyrunnable (); //starting the thread, because there is no Start method in Runnable, you should start the thread by taking your runnable instance as the thread (target target) parameter .//with a runnable instance, create 3 threads, and the three threads share tickets this resource        NewThread (myRunnable1, "window number 1th"). Start (); NewThread (myRunnable1, "window number 2nd"). Start (); NewThread (myRunnable1, "window number 3rd"). Start (); }}

Output: Three threads shared 5 tickets

The use of instantiating a Runnable object for sharing

3. It is noted that in multithreaded development, the main thread and the child threads are executed concurrently, that is, the main thread is executing in the process of executing the child threads. This leads to the need for such a poor realization. That is, the main thread needs all the child threads to return to the execution result to continue execution. Comrades, how can this be achieved?

OK, we use a countdownlatch to achieve

1  Public classMyrunnablereturnImplementsRunnable {2     PrivateCountdownlatch Threadssingal;3 4 5      PublicMyrunnablereturn (Countdownlatch threadssingal) {6         Super();7          This. Threadssingal =Threadssingal;8     }9 Ten  One      Public voidrun () { ASystem.out.println (Thread.CurrentThread (). GetName () + "--Start"); -System.out.println (Thread.CurrentThread (). GetName () + "--end"); -Threadssingal.countdown ();//thread minus 1 the     } -  -      Public Static voidmain (String [] agrs) { -System.out.println ("Main--Start"); +Countdownlatch threadssingal=NewCountdownlatch (3); -Myrunnablereturn myrunnable=NewMyrunnablereturn (threadssingal); +         NewThread (myrunnable, "Thread1"). Start (); A         NewThread (myrunnable, "Thread2"). Start (); at         NewThread (myrunnable, "Thread3"). Start (); -         Try { -Threadssingal.await ();//waits for all child threads to finish executing -}Catch(interruptedexception e) { -             //TODO auto-generated Catch block - e.printstacktrace (); in         } -System.out.println ("Main--end"); to     } +}

Output: The main thread waits for all child threads to finish executing, and then executes the

4. The problem has come, in reality development, it is possible to need different runnable according to different data to execute the same code, how does this happen?

This, in turn, causes the method of sharing resources by instantiating only one Runnable object to be done. We can pass the shared data to a different Runnable thread object by encapsulating it as an object. Achieve resource sharing

Java multi-threaded, main thread waits for all child threads to complete, share resources

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.