In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the Java Condition class example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.
Introduction of condition and demo
Condition only appeared in java 1.5.It is used to replace traditional Object's wait () and notify () to realize inter-thread cooperation. Compared with wait () and notify () using Object, it is safer and more efficient to use Condition's await () and signal () to achieve inter-thread cooperation. Therefore, it is generally recommended to use Condition, and the blocking queue actually uses Condition to simulate inter-thread collaboration.
Condition is an interface, and the basic methods are await () and signal ().
Condition depends on the Lock interface, and the basic code for generating a Condition is lock.newCondition ()
Calling the await () and signal () methods of Condition must be within the protection of lock, that is, they can only be used between lock.lock () and lock.unlock.
The await () in Conditon corresponds to the wait () of Object
The signal () in Condition corresponds to the notify () of Object
The signalAll () in Condition corresponds to the notifyAll () of Object.
A common example of condition, arrayblockingqueue. Here is the demo:
Package thread; import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;/** @ author zhangliang * * 5:48:54 on April 8, 2016 * / public class ConTest {final Lock lock = new ReentrantLock (); final Condition condition = lock.newCondition () Public static void main (String [] args) {/ / TODO Auto-generated method stub ConTest test = new ConTest (); Producer producer = test.new Producer (); Consumer consumer = test.new Consumer (); consumer.start (); producer.start () } class Consumer extends Thread {@ Override public void run () {consume () } private void consume () {try {lock.lock (); System.out.println ("I'm waiting for a new signal" + this.currentThread () .getName ()) Condition.await ();} catch (InterruptedException e) {/ / TODO Auto-generated catch block e.printStackTrace () } finally {System.out.println ("get a signal" + this.currentThread (). GetName ()); lock.unlock () } class Producer extends Thread {@ Override public void run () {produce () } private void produce () {try {lock.lock (); System.out.println ("I got the lock" + this.currentThread () .getName ()) Condition.signalAll (); System.out.println ("I sent a signal:" + this.currentThread (). GetName ());} finally {lock.unlock () }
Running result:
The execution mode of Condition is that when the await method is called in the thread Consumer, the thread Consumer releases the lock and sleeps itself, waits for it to wake up, and the thread Producer acquires the lock and starts to do things. After it is finished, the signalall method of Condition is called to wake up the thread Consumer, and the thread Consumer resumes execution.
The above shows that Condition is a tool class for coordinating communication between multiple threads, so that one or some threads wait together for a condition (Condition). Only when the condition is met (signal or signalAll method is called), these waiting threads will be awakened to re-compete for the lock.
Condition implements the producer and consumer model:
Package thread; import java.util.PriorityQueue;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock; public class ConTest2 {private int queueSize = 10; private PriorityQueue queue = new PriorityQueue (queueSize); private Lock lock = new ReentrantLock (); private Condition notFull = lock.newCondition (); private Condition notEmpty = lock.newCondition () Public static void main (String [] args) throws InterruptedException {ConTest2 test = new ConTest2 (); Producer producer = test.new Producer (); Consumer consumer = test.new Consumer (); producer.start (); consumer.start (); Thread.sleep (0) Producer.interrupt (); consumer.interrupt ();} class Consumer extends Thread {@ Override public void run () {consume ();} volatile boolean flag=true Private void consume () {while (flag) {lock.lock () Try {while (queue.isEmpty ()) {try {System.out.println ("queue is empty, waiting for data"); notEmpty.await () } catch (InterruptedException e) {flag = false;}} queue.poll () / / each time the first element of the queue is moved, notFull.signal (); System.out.println ("take an element from the queue, queue remaining" + queue.size () + "element");} finally {lock.unlock () } class Producer extends Thread {@ Override public void run () {produce ();} volatile boolean flag=true Private void produce () {while (flag) {lock.lock () Try {while (queue.size () = = queueSize) {try {System.out.println ("queue full, waiting for free space"); notFull.await () } catch (InterruptedException e) {flag = false;}} queue.offer (1) / / insert one element at a time notEmpty.signal (); System.out.println ("insert an element into the queue, queue remaining space:" + (queueSize-queue.size ();} finally {lock.unlock () }
Running result:
Two Condition interface
Condition can be popularly understood as conditional queue. When a thread calls the await method, it is not awakened until a condition that the thread waits for is true. This approach provides a simpler wait / notification mode for threads. Condition must be used with locks because access to shared state variables occurs in a multithreaded environment. An instance of Condition must be bound to a Lock, so Condition is generally implemented as an internal Lock.
Await (): causes the current thread to wait until it is signaled or interrupted.
Await (long time, TimeUnit unit): causes the current thread to wait until it is signaled, interrupted, or reaches a specified wait time
AwaitNanos (long nanosTimeout): causes the current thread to wait until it is signaled, interrupted, or reaches the specified wait time. The return value indicates the remaining time. If you wake up before nanosTimesout, the return value = nanosTimeout-elapsed time, if the return value is
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.