Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does Java use Condition to control thread communication

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is about how Java uses Condition to control thread communication. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

The details are as follows:

A little bit of eye contact

When using the Lock object to ensure synchronization, Java provides a Condition class to maintain coordination, using Condition allows threads that have got the Lock object but cannot continue to execute to release the Lock object, and the Condtion object can also wake up other waiting threads.

Condition decomposes the synchronous monitoring lock methods (wait, notify, and notifyAll) into distinct objects to provide multiple wait sets (wait-set) for each object by combining them with Lock objects. In this case, Lock replaces the synchronization method or synchronization code block, and Condition replaces the function of synchronization monitoring locks.

The Condition instance is essentially bound to a Lock object. To get a Condition instance of a specific Lock instance, call the Lock object newCondition () method. The Condtion class provides the following three methods:

Await (): similar to the wait () method on the implicit synchronization monitor, causes the current thread to wait until another thread calls the signal () method or the signalAll () method of the Condtion to wake up the thread. There are more variants of this await method: long awaitNanos (long nanosTimeout), void awaitUninterruptibly (), awaitUntil (Date deadline), etc., which can complete more abundant wait operations.

Signal (): wakes up a single thread waiting on this Lock object. If all threads are waiting on the Lock object, one of them is chosen to wake up. The choice is arbitrary. The awakened thread can be executed only after the current thread abandons the lock on the Lock object (using the await () method).

SignalAll (): wakes up all threads waiting on this Lock object. The awakened thread can be executed only if the current thread abandons the lock on the Lock object.

Two code

1 Account class

Public class Account {/ / explicitly defines the Lock object private final Lock lock = new ReentrantLock (); / / gets the Condition private final Condition cond = lock.newCondition () corresponding to the specified Lock object; / / encapsulates the account number and two member variables private String accountNo; private double balance; / / indicating whether there is a deposit in the account private boolean flag = false Public Account () {} / / Constructor public Account (String accountNo, double balance) {this.accountNo = accountNo; this.balance = balance;} / / setter and getter methods public void setAccountNo (String accountNo) {this.accountNo = accountNo;} public String getAccountNo () {return this.accountNo;} / / so account balances are not allowed to be modified casually, so only getter methods are provided for balance, public double getBalance () {return this.balance } public void draw (double drawAmount) {/ / locked lock.lock (); try {/ / if flag is false, indicating that no one has deposited money in the account, and the withdrawal method blocks if (! flag) {cond.await ();} else {/ / execute System.out.println (Thread.currentThread (). GetName () + "withdraw:" + drawAmount); balance-= drawAmount; System.out.println ("account balance:" + balance) / / set the flag to false to identify whether the account already has a deposit. Flag = false; / / Wake up other threads cond.signalAll ();}} catch (InterruptedException ex) {ex.printStackTrace ();} / / use the finally block to release the lock finally {lock.unlock ();}} public void deposit (double depositAmount) {lock.lock (); try {/ / if flag is true, indicating that someone has deposited money in the account, the saving method blocks if (flag) / / ① {cond.await () } else {/ / execution deposit System.out.println (Thread.currentThread (). GetName () + "deposit:" + depositAmount); balance + = depositAmount; System.out.println ("account balance:" + balance); / / set the flag indicating whether the account has a deposit to true flag = true; / / wake up other threads cond.signalAll ();}} catch (InterruptedException ex) {ex.printStackTrace () } / / use the finally block to release the lock finally {lock.unlock ();}} / / the following two methods override the hashCode () and the equals () method public int hashCode () {return accountNo.hashCode ();} public boolean equals (Object obj) {if (this = = obj) return true; if (obj! = null & & obj.getClass () = = Account.class) {Account target = (Account) obj; return target.getAccountNo (). Equals (accountNo);} return false;}}

2 DrawThread thread class

Public class DrawThread extends Thread {/ / simulate user account private Account account; / / the amount of money that the current withdrawal thread wants to withdraw private double drawAmount; public DrawThread (String name, Account account, double drawAmount) {super (name); this.account = account; this.drawAmount = drawAmount;} / / repeat the withdrawal operation public void run () {for (int I = 0; I < 100; iTunes +) {account.draw (drawAmount);}

3 DepositThread thread class

Public class DepositThread extends Thread {/ / simulate user account private Account account; / / the amount of money the current withdrawal thread wants to deposit private double depositAmount; public DepositThread (String name, Account account, double depositAmount) {super (name); this.account = account; this.depositAmount = depositAmount;} / / repeat the deposit operation public void run () {for (int I = 0; I < 100; iDeposit +) {account.deposit (depositAmount);}

4 test class

Public class DrawTest {public static void main (String [] args) {/ / create an account Account acct = new Account ("1234567", 0); new DrawThread ("withdrawals", acct, 800). Start (); new DepositThread ("depositor A", acct, 800). Start (); new DepositThread ("depositor B", acct, 800). Start (); new DepositThread ("depositor C", acct, 800). Start ();}}

Three running results

. Depositor C deposit: 0 account balance: 0 withdrawals: 800.0 account balances: 800.0 depositors A deposits: 800.0 account balances: 800.0 withdrawals: 800.0 account balances: 800.0 depositors C deposits: 800.0 account balances: 800.0 withdrawals: 800.0 account balances: 800.0 depositors A deposit: 800.0 account balance: 800.0 withdrawals: 800.0 account balance: 800.0 depositors C deposits: 800.0 account balances: 800.0 withdrawals: 800.0 account balances: 800.0 depositors A deposits: 800.0

Thank you for reading! This is the end of this article on "how Java uses Condition to control thread communication". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report