Five methods of thread waiting (synchronization) in Java, five methods of java

Source: Internet
Author: User
Tags thread logic

Five methods of thread waiting (synchronization) in Java, five methods of java

During the interview, the interviewer often asked how to execute the business logic of the main thread after a main thread has multiple sub-threads. I can think of five methods to solve this problem. For details, see the source code.

1. Use the join method inherent in the Thread class to add the Sub-thread to the main thread. After the sub-thread is executed, the main thread logic is executed.

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. Use the CountDownLatch class in the concurrent JDK package and CountDownLatch. Each thread calls its countDown method to enable counter-1. The main thread calls the await method to block the wait, the execution continues until the CountDownLatch counter is 0, for example

First, define the sub-Thread

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 Date (); new ThreadWaitDemo (). doSomeWork (); // do the actual work System. out. println ("Sub Worker" + workerName + "do work complete at" + sdf. format (new Date (); latch. countDown (); // After the counter is completed, subtract one }}

Investigate await method blocking wait in the main thread until all threads are finished

Public static void countDownLatchDemo () throws InterruptedException {System. out. println ("========= Test with CountDownLatch ====="); CountDownLatch latch = new CountDownLatch (2 ); worker worker1 = new CountDownLatchWorker ("worker1", latch); CountDownLatchWorker worker2 = new CountDownLatchWorker ("worker2", latch); worker1.start (); worker2.start (); // The main thread is blocked and waits for latch. await (); doSuperWork ();}

3. Use JDK and send the package CyclicBarrier. CyclicBarrier is similar to CountDownLatch and is also a counter. The difference is that the await () method of CyclicBarrier is not called once, and the count is reduced by 1, and block the current thread. When the count is reduced to 0, the blocking is removed, and all the threads blocked on this javasicbarrier start to run. After that, if you call the await () method again, the count will become a N-1, and a new round of restarting icbarrier can also bring a Runnable parameter at the beginning, this Runnable task is executed before all other threads are awakened when the number of javasicbarrier reaches.

Example:

Public static void javasicbarrierdemo () throws InterruptedException, BrokenBarrierException {System. out. println ("========= Test with your icbarrier ====="); CyclicBarrier cb = new CyclicBarrier (2, new Runnable () {// put the main thread business in the javasicbarrier constructor. When all threads reach the Barrier, execute @ SuppressWarnings ("static-access") public void run () {new ThreadWaitDemo (). doSuperWork () ;}}); // you need to wait for two threads to ExecutorService executor = Executors. newFixedThreadPool (2); CyclicBarrierWorker worker1 = new CyclicBarrierWorker ("worker1", cb); worker worker2 = new worker ("worker2", cb); executor.exe cute (worker1 ); executor.exe cute (worker2); executor. shutdown ();}

4. Use the Executors framework in the JDK and release package, and use the invokeAll method of ExecutorService to investigate the callable set. Multiple Threads are executed in batch. After the invokeAll method is completed, other business logic of the main thread is executed.

Example:

Public static void callableDemo () throws InterruptedException {System. out. println ("========= Test with Callable ==== "); list <Callable <Integer> callList = new ArrayList <Callable <Integer> (); ExecutorService exec = Executors. newFixedThreadPool (2); // callList is implemented using an anonymous internal class. add (new Callable <Integer> () {public Integer call () throws 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 work 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 work complete at" + sdf. format (new Date (); return 0 ;}}); exec. invokeAll (callList); exec. shutdown (); doSuperWork ();}
5. This is too disgusting. Let's just talk about the method. The main thread creates a thread List, stores each subthread in the List, and regularly polls the subthread status in the List, after All threads are completed, execute the main thread logic.



Java Thread Synchronization Method

Wait for wake-up Mechanism
Wait (): Let the thread wait. Stores threads in a thread pool.
Running y (): Wake up the waiting thread. Usually wake up the first thread in the thread pool. Temporarily blocks the wake-up thread.
Yyall (): wake up all the waiting threads. Wake up all threads in the thread pool and turn them from the frozen body to the temporary blocking status.
These three methods are used to operate the thread, but are defined in the Object class. Why?
These three methods need to be defined in synchronization when used, and the thread operated by these methods must be clear.
To put it simply. In the thread where A lock is wait, it can only be awakened by the notify method of A lock.
Therefore, the Lock Object of the wait notify method must be indicated, and the lock object can be any object.
Methods that can be called by any Object must be defined in the Object class.
Note: The wait for wake-up mechanism is usually used in synchronization because the lock is required.
In addition, you must specify the Lock Object for wait notify.

The lock after JDK1.5

After jdk1.5,
Some new features have emerged, and the principle thread has been improved.
An interface Lock is provided in the java. util. concurrent. locks package. Synchronized is replaced.
Synchronized. The lock operation is implicit.
The Lock operation is displayed.
There are two methods to accomplish this:
Lock (): Get the lock.
Unlock (): Release the lock.
There is also an object, Condition.
The appearance of this Object replaces the methods of the wait monitoring y policyall operations monitor in the Object.
Alternative method: await signal signalAll.

Simple Method for writing thread synchronization (java)

/**
* Java thread: synchronization of threads
*
* @ Author leizhimin 2009-11-4 11:23:32
*/
Public class Test {
Public static void main (String [] args ){
User u = new User ("James", 100 );
MyThread t1 = new MyThread ("thread A", u, 20 );
MyThread t2 = new MyThread ("thread B", u,-60 );
MyThread t3 = new MyThread ("thread C", u,-80 );
MyThread t4 = new MyThread ("thread D", u,-30 );
MyThread t5 = new MyThread ("thread E", u, 32 );
MyThread t6 = new MyThread ("thread F", u, 21 );
T1.start ();
T2.start ();
T3.start ();
T4.start ();
T5.start ();
T6.start ();
}
}
Class MyThread extends Thread {
Private User u;
Private int y = 0;
MyThread (String name, User u, int y ){
Super (name );
This. u = u;
This. y = y;
}
Public void run (){
U. Random (y );
}
}
Class User {
Private String code;
Private int cash;
User (String code, int cash ){
This. code = code;
This. cash = cash;
}
Public String getCode (){
Return code;
}
Public void setCode (String code ){
This. code = code;
}
/**
* Business methods
* @ Param x Add x million RMB
*/
Public synchronized void merge (int x ){
Try {
Thread. sleep (10L );
This. cash + = x;
System. out. println (Thread. currentThread (). getName () + "run ended. Add" + x + "". The current user account balance is: "+ cash );
Thread. sleep (10L );
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
@ Override
Public Str... the remaining full text>

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.