Java Concurrency Programming (eight) inter-thread collaboration (top)

Source: Internet
Author: User

When multithreading is performed concurrently, there may be dependencies between the contents of different threads, such as thread one executes the A () method and the C () method, thread two executes the B () method, method A () must be executed before method B (), and Method C () must be executed after Method B (). At this point two threads need to collaborate to complete this task, so that two threads collaboration has a simple brute method, that is, monitoring the Boolean variable, the code is as follows:

Boolean false ; Boolean false;

Thread one executes the following code:

true ;  while (! FINISHB) {}c ();

Thread two executes the following code:

 while (!  true;

Both the B () method and the C () method are checked to see if the dependent method execution ends, and only the dependent method execution ends before jumping out of the loop. The advantage of this method is that it is simple and rude, the disadvantage is that the thread is in a busy state when waiting for the dependent method, that is, the thread is running (CPU time is consumed) but it is not doing anything meaningful, the better way is to block it when the threads wait, blocking the state without consuming CPU time. To improve CPU utilization.

Collaborate with built-in locks

Java provides a mechanism for inter-threading collaboration, namely the Object.wait () method, the Object.notify (), and the Object.notifyall () methods.

Wait () method: Causes the current thread to block and waits for other threads to call the Notify () method to release the currently acquired lock.

Notify () Method: Wakes up a waiting thread, the thread wakes up and attempts to acquire the lock, and the other threads continue to wait.

Notifyall () method: Wakes all waiting threads to attempt to acquire locks, which are queued for lock.

Use these methods to give a small example, students go to the canteen to eat a bowl first, and then give the bowl to Aunt Sheng fan, Aunt Sheng Rice bowl back to classmates, this time students can eat, with code simulation This example is as follows:

classStudentImplementsRunnable { Public voidrun () {synchronized(Cafeteriatest.wan) {System.out.println ("Student: Take a bowl."); System.out.println ("Student: Aunt Help Sheng Fan");            CafeteriaTest.wan.notify (); Try{CafeteriaTest.wan.wait (); } Catch(Interruptedexception e) {} System.out.println ("Student: Dinner"); }    }}classCafeteriaworkerImplementsRunnable { Public voidrun () {synchronized(Cafeteriatest.wan) {Try{CafeteriaTest.wan.wait (); } Catch(Interruptedexception e) {} System.out.println ("Aunt: Sheng Fan for students");        CafeteriaTest.wan.notify (); }    }} Public classCafeteriatest { Public StaticObject wan =NewObject ();  Public Static voidMain (string[] args)throwsinterruptedexception {executorservice exec=Executors.newcachedthreadpool (); Exec.execute (NewCafeteriaworker ()); Thread.Sleep (100);//wait till Auntie's ready.Exec.execute (NewStudent ());    Exec.shutdown (); }}

The output results are as follows:

Student: Take a bowl

Student: Aunt Help Sheng Fan

Aunt: Sheng Fan for students

Student: Dinner

The example first creates an "Aunt Thread", which first acquires a "bowl" lock and then calls the Wait () method to enter the blocking state and release the lock. Then we created the "Student Thread", the student first printed the bowl, then called the Notify () method to notify the "Aunt Thread" Sheng fan, and called the Wait () method to make the current thread release the lock and block it, then the "Aunt thread" resumes from the blocking state to the student's meal, then the "Auntie Thread" calls notify () method informs the student to finish the meal, "Aunty thread" runs the end and releases the lock, "student thread" got the "bowl lock" to start eating.

There are three points to note in this process:

1. You must use the Synchronized keyword to obtain the lock on the object before calling the Wait () and notify () methods, or the system throws an exception. Therefore, these methods cannot be called within a critical section that uses a display lock.

2. After calling the wait () method, there are two factors that prevent the thread from executing: 1. The thread is in a blocking state because it waits for the Notify () method. 2. After obtaining notification of the Notify () method, an attempt is made to acquire the lock, at which point the lock may be unavailable, and the thread is blocked by waiting for the other thread to release the lock.

3. Make sure that the "Auntie Thread" gets the lock first, and if the "student thread" first gets the lock, the "Auntie Thread" will be blocked by not getting the lock until the "student thread" executes to the Wait () method, but the Notify () method has been called before, and "Auntie Thread" did not execute to the wait () method , missed the "student thread" sent to the signal.

Collaborating with display locks

The Wait (), notify () method of an object must be called before the lock of the object is invoked, but the lock of a particular object cannot be obtained by using the displayed lock, so the methods cannot be used within the critical section of the display lock. The display lock provides us with another thread-collaboration mechanism similar to the wait () and notify () method, which is exactly the same as the Wait () and notify () methods, and we use this method to rewrite the example of a student's meal:

classStudentImplementsRunnable { Public voidrun () {CafeteriaLockTest.lock.lock (); Try{System.out.println ("Student: Take a bowl."); System.out.println ("Student: Aunt Help Sheng Fan");            CafeteriaLockTest.wan.signal ();            CafeteriaLockTest.wan.await (); System.out.println ("Student: Dinner"); } Catch(Interruptedexception e) {}finally{CafeteriaLockTest.lock.unlock (); }    }}classCafeteriaworkerImplementsRunnable { Public voidrun () {CafeteriaLockTest.lock.lock (); Try{CafeteriaLockTest.wan.await (); System.out.println ("Aunt: Sheng Fan for students");        CafeteriaLockTest.wan.signal (); }        Catch(Interruptedexception e) {}finally{CafeteriaLockTest.lock.unlock (); }    }} Public classCafeterialocktest { Public StaticLock lock =NewReentrantlock ();  Public StaticCondition Wan;  Public Static voidMain (string[] args)throwsInterruptedexception {Wan=lock.newcondition (); Executorservice exec=Executors.newcachedthreadpool (); Exec.execute (NewCafeteriaworker ()); Thread.Sleep (100);//wait till Auntie's ready.Exec.execute (NewStudent ());    Exec.shutdown (); }}

The output results are as follows:

Student: Take a bowl

Student: Aunt Help Sheng Fan

Aunt: Sheng Fan for students

Student: Dinner

In the code, we define a re-entry lock object as a common lock for two threads, and call the Lock.newcondition () method to get a condition object for multi-threaded collaboration, and the condition await () method is equivalent to the wait of object () method, the signal () method is equivalent to the Notify () method of object, and condition also has a signalall () method equivalent to the Notifyall () method of object. One thing to note is that you should not misuse the wait () method when calling the await () method of condition.

Summarize

This section describes how to enable multiple threads to collaborate on a task, where the Wait () method is similar to the previous Thread.Sleep () method, both of which cause the thread to be blocked, but the wait () method requires that the object's built-in lock must be fetched before the call, sleep () There is no precondition for a method call, and another difference is that the wait () method call frees the object's lock, and the sleep () method does not release the lock. Collaboration between threads has not been continued.

Public number: Today said yards. Follow my public number to see the serial article. If you do not understand the problem, directly in the public message can be.

Java concurrency Programming (eight) inter-thread collaboration (top)

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