Multithreaded communication method of java classic interview questions

Simply sort it out and update it later. . . . .

Java multi-thread communication is generally implemented in the following ways:

1. Traditional thread communication synchronized + wait + notify

The wait (), notify () and notifyAll () methods of the Object class must be called by the synchronous monitor object. There are two cases:

a) Synchronization method, the default instance of this class (this) is the synchronization monitor, which can be called directly in the synchronization method

b) The synchronization code block, the synchronization monitor is the object in the brackets after being synchronized, so you must use this object to call these three methods

 

Second, use Condition to control thread communication lock + condition + await + signal

Lock replaces the synchronization method or synchronization code block, and Condition replaces the function of the synchronization monitor.

private final Lock lock = newReentrantLock();

private final Condition con =lock.newCondition();

lock.lock();   con.await();    con.signalAll();    lock.unlock():

 

Three, use blocking queue (BlockingQueue) to control thread communication

The BlockingQueue interface is mainly used as a tool for thread synchronization. When the producer tries to put an element into the BlockingQueue, the thread is blocked if the queue is full; when the consumer tries to get the element into the BlockingQueue, if the queue is empty, the thread is blocked.

 

81 original articles published · Like 29 · Visitors 20,000+

Guess you like

Origin blog.csdn.net/breakout_alex/article/details/105465112