Communication between multiple threads (methods to wait for a wake-up mechanism, Lock, and other threads)

Source: Internet
Author: User
Tags thread class

One, the communication between multithreading.

Is that multiple threads are manipulating the same data, but the methods of operation are different.

For example: For the same storage block, there are two storage bits: Name sex, existing two threads, one to which data is stored, and one to print.

In order to solve the security problem in the above problem (the print thread cannot manipulate the common data while the storage thread is holding the operation), the two threads should be
Synchronize the code portion of the common data (using synchronized () to synchronize, note: Use the same object as the synchronization lock.

Second, wait for the wake-up mechanism.

After the implementation of the above-mentioned cases, it is found that the order of printing results is not in the order of storage, so the waiting wake-up mechanism is introduced here.

Explanation: After a thread has made a specified operation, it enters the wait state (Wait ()), waits for other threads to execute their specified code before waking it Up (notify ()).
When there are multiple threads waiting, you can use Notifyall () to wake up all the waiting threads, if necessary.

The method used (keyword):
The object name, wait (), causes the current thread to wait before another thread calls this object's notify () method or the Notifyall () method.
The object name. Notify (); Wakes a single thread waiting on this object monitor.
The object name. Notifyall (); Wakes all the threads waiting on this object monitor.


    
Note: The above method (keyword) must be used in synchronization because it needs to operate on the thread holding the object monitor ownership (lock).
So it must be used in synchronization, because only the line friend in the synchronization has ownership (lock) of that object monitor,

Wait () and sleep () will throw interruptedexception exceptions.

Also, the above methods are defined in the class: Object

Because these methods must indicate the locks held by the thread on which they are operating (called by the object of the lock) when manipulating the threads in the synchronization.
And only the waiting thread under the same object monitor (the same lock) can be awakened by the thread holding the lock (unable to wake the different locked threads)
That is, the thread that waits and wakes must be under the same object's monitor (the same lock).
A lock can be any object that is almost certain, and the method that can be called by any object should be defined in the object class.


Monitor (lock): The thread of the same object's monitor (the same lock) can only execute one at a time: that is, the one that owns the monitor ownership (holding the lock).


Third, interface lock and interface condition

Note: When using lock and condition, the toolkit must be introduced: Import java.util.concurrent.locks.*

Above jdk1.5, in order to solve the security problem when multiple threads are simultaneously doing different operations on a shared data (either in a state where all threads are waiting at the same time,

Or every time you wake up the problem of waiting threads),
It provides us with a new lock tool: Lock to replace synchronized, the condition object created by the lock object that is bound to the lock object

   replaces the wait,notify operation in the object class.


1, lock interface, class known to implement the interface: Reentrantlock, Reentrantreadwritelock.readlock, Reentrantreadwritelock.writelock

1), Reentrantlock (roughly functionally equivalent to synchronized, but can bind multiple condition)


Construction Method: Reentrantlock () creates an instance of Reentrantlock.
Reentrantlock (Boolean fair) creates a Reentrantlock

Common method with a given fairness policy: Voidlock (): Gets a lock.
 voidunlock (): Releases the lock.
 conditionnewcondition () returns the Condition instance used with this Lock instance.




2, Contition interface, known implementation class: Abstractqueuedlongsynchronizer.conditionobject, Abstractqueuedsynchronizer.conditionobject (temporarily not learning)

Common method: Voidawait () causes the current thread to wait until it is signaled or interrupted.
Voidsignal () wakes up a waiting thread.
Voidsignalall () wakes all waiting threads.


Common code example:
Class Boundedbuffer {
Final lock lock = new Reentrantlock ();//Gen Create a lock Subclass object lock
Final Condition notfull = Lock.newcondition ();//Call the Newcondition method of lock, creating a Condition subclass Object Notfull
Final Condition notempty = Lock.newcondition ();//Call the Newcondition method of lock to create a Condition subclass object Notempt Y

public void put (Object x) throws Interruptedexception {//
Lock.lock (); Get lock
try {
while (Judgment statement)
Notfull.await ();//judgment succeeds, thread waits for notfull.

Operation code

Notempty.signal ();//wakes up the waiting thread under Notempty.
finally {//guarantees that the subsequent statement executes.
Lock.unlock ();//Release lock.
}
}

Public Object take () throws Interruptedexception {
Lock.lock ();
try {
while ()
Notempty.await ();
Operation code
Notfull.signal ();

} finally {
Lock.unlock ();
}
}
}



Four, stop the thread

Note: The Stop method exists in the previous version of the JDK, but in the new version. This method is obsolete.

How the thread stops: The thread is automatically stopped when the code in the Run method finishes executing.

1, when the thread is the loop code, as long as the control loop end, you can end the thread.

Special case: When a thread has a wait () statement or an await () statement, it causes the thread to freeze so that the code or tag that controls the loop ends cannot be executed or read.

Then the thread will not end.

When all threads are frozen and no method is specified to unfreeze, we are forced to clear the frozen state so that the tag can be manipulated to end the loop.

This method is provided in the thread class: the Interrupt () method,(the wait statement itself will have a interrptedexception exception,

as long as the interrupt method interrupts the freeze, it throws this exception, we can to establish a loop-ending tag in an exception-handling statement).



Five, The Guardian thread

There is a method in the thread class that calls the method and passes in true to define the thread as a daemon thread (background thread).
The method is: Voidsetdaemon (Boolean on) marks the thread as either a daemon thread or a user thread. (Should pass in true when called).

Note: 1. Mark the thread as a daemon thread or a user thread. When a running thread is a daemon thread, the Java virtual machine exits.
(that is, the background thread relies on the foreground thread)

2. The method must be called before the thread is started.

Example: Thread t = new thread ();
T.setdaemon (TRUE);
T.start ();
The thread t at this time is the daemon thread.


Vi. Join method.

VPI Explanation: Voidjoin () waits for the thread to terminate.

When thread a executes, a thread of B is encountered. When the Join method is executed, the a threads wait for the B thread to execute until it finishes executing.
(When a parameter is passed in when the Join method is called: Long Millis, the A thread waits for the B thread to execute for a maximum of millis milliseconds.) )

Join can be used to temporarily join thread execution.

Communication between multiple threads (methods to wait for a wake-up mechanism, Lock, and other threads)

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.