Thread Communication (Wait (), notify (), Notifyall () method)

Source: Internet
Author: User
Tags thread class

Thread Communication:

Programs cannot control the rotation of threads, but there are mechanisms to ensure that threads work in harmony.

Traditional thread Communication
The object class provides wait (), notify () and Notifyall () three methods to implement thread communication, which are not part of the thread class.

1. Wait (): The current thread waits until the other thread invokes the Notify () or Notifyall () method of the synchronization monitor to wake the thread (or you can specify a wait time). * Invoking the Wait () method frees the current thread from locking the synchronization monitor. 
2. Notify (): Wakes up a single thread waiting on this synchronization monitor. If multiple threads are waiting on this synchronization monitor, one is randomly awakened. The awakened thread can only be executed when the front thread discards the lock on the monitor (with the Wait () method). 
3. Notifyall (): Wakes all threads waiting on this synchronization monitor. The awakened thread can only be executed when the front thread discards the lock on the monitor (with the Wait () method). 

Wait (), the Notify () and Notifyall () methods are invoked by the synchronization monitor object:
* * Synchronized-decorated synchronization method, because the default instance (this) is the synchronization monitor itself, so you can use these three methods directly.
* * The synchronized code block decorated with synchronized, which is the object after synchronized parentheses, must be used by the object caller three methods.

Program instance:
Suppose there are two threads in the system now, these two threads represent depositors and withdrawals, and now assume that the system has a special system that requires depositors and withdrawals to repeatedly save money, and that withdrawals are immediately withdrawn whenever a depositor saves money.
* * The procedure can be a flag to indicate whether there is a deposit in the account, when the flag is false, indicating that there is no deposit in the account, the depositor thread can execute downward, and when the depositor deposits the money in the account, set the flag to True and Invoke notify () or Notifyall () method to wake the other thread, and when the depositor enters the thread execution body, call the Wait () method to await it if the flag is true.
* * When the flag is true, indicates that there is a deposit in the account, the teller thread can be executed downward, when the teller takes the money out of the account, set the flag to false, and invoke the Notify () or Notifyall () method to wake the other thread, and when the teller enters the thread execution body, If the flag is false, call the Wait () method to keep it waiting.

* * This procedure provides the account class with draw () and deposit () two methods, respectively, for the accounts of the savings and money operations, because these two methods may need to be modified concurrently to modify the value of the balance member variable, So both methods use synchronized to modify the synchronization method, and in addition, the two methods use Wait () Notifyall () to control the collaboration of the threads.

Package Com.bank;
     public class Accounts {//Encapsulates account number, account balance two member variables private String accountno;
     private double balance;

     Flag Private Boolean Flag=false that identifies whether there is a deposit in the account; Public account () {}//Builder Public account (String accountno,double balance) {this.accountno=
           Accountno;
     This.balance=balance;
     Public String Getaccountno () {return this.accountno;
     } public void Setaccountno (String accountno) {this.accountno = Accountno;
     //account balances are not allowed to be arbitrarily modified, so only the getter method is provided for balance public double getbalance () {return this.balance; Public synchronized void Draw (double drawamount) {//If flag is false, indicating that no money has been deposited in the account, the method of taking money blocks the try  {if (!
           Flag) {wait (); else{//Execute SYSTEM.OUT.PRINTLN (Thread.curre
 Ntthread () getName () + "Withdraw money:" +drawamount);                        Balance=balance-drawamount;
                         System.out.println ("The Balance is:" +balance);
                         Set the flag of the identity account to false flag= false;
                     Wake Up Other threads notifyall ();
                     The catch (Interruptedexception e) {//TODO auto-generated catch block
                E.printstacktrace ();
           } public synchronized void deposit (double depositamount) {//If flag is true, it means that the account is rich and the saving method is blocked
                try{if (flag) {wait (); }//Perform deposit Operation else{System.out.println (Thread.CurrentThread (). GetName () +
                     "Deposit" +depositamount);
                     Balance=balance+depositamount;
                     System.out.println ("Account balance is:" +balance); Set the flag of the identity account deposit to true FLAG=true;
                Wake Up Other threads notifyall ();

           }}catch (Interruptedexception e) {e.printstacktrace ();
           @Override public int hashcode () {final int prime = 31;
           int result = 1;
           result = Prime * result + ((Accountno = null)? 0:accountno.hashcode ());
           Long temp;
           temp = double.doubletolongbits (balance);
           result = Prime * result + (int) (temp ^ (temp >>> 32));
     return result;
           @Override public boolean equals (Object obj) {if (this = obj) return true;
           if (obj = null) return false;
           if (GetClass ()!= Obj.getclass ()) return false;
           Account other = (account) obj;
           if (Accountno = = null) {if (Other.accountno!= null) return false; else if (!accounTno.equals (Other.accountno)) return false;
           if (double.doubletolongbits (balance)!= double.doubletolongbits (other.balance)) return false;
     return true;
 }

}

Program thread loops 100 times to repeat deposits, while the pickup threads repeat 100 withdrawals, and the depositor and Teller threads invoke the deposit () and draw () methods of the Account object respectively to implement the

Package Com.bank;
     public class Drawthread extends thread{//mock user accounts private account;
     The amount of money currently required for a thread is private double drawamount;
           Public Drawthread (String name,account account,double drawamount) {super (name);
           This.account=account;
     This.drawamount=drawamount; //Repeat the 100-time fetch operation public void Run () {for (int i = 0; i < i++) {Account.draw
           (Drawamount);
}} package Com.bank;
           public class Depositthread extends Thread {//mock user accounts private account;
           The amount of money that the current saving thread needs is private double depositamount;
                Public Depositthread (String name,account account,double depositamount) {super (name);
                This.account=account;
           This.depositamount=depositamount;
 //Repeat 100 saving operations public void run () {for (int i = 0; i < i++) {                    Account.deposit (Depositamount);

 }
           }
}

The main program can start any number of deposit and withdrawal threads. You can see all the thread must wait until the money line Cheng after the end of the payment can be executed, and the saving thread must wait for the money thread to take money before it can be executed.

Package Com.bank;
public class Drawtest {public
     static void Main (string[] args) {
           //Create account
           accounts  acct  =new Accounting (" 1234567 ", 0);
           New Drawthread ("Money-seekers", acct,). Start ();
           New Depositthread ("Savers 1", acct). Start ();
           New Depositthread ("Savers 2", acct). Start ();
           New Depositthread ("Savers 3", acct). Start ();
     }

The results are as follows:

Savers 1 Deposit 800.0
Account balance is: 800.0
Withdraw money to withdraw money: 800.0
The remaining balance is: 0.0
Savers 3 Deposit 800.0
Account balance is: 800.0
Withdraw money to withdraw money: 800.0
The remaining balance is: 0.0
Savers 1 Deposit 800.0
Account balance is: 800.0
Withdraw money to withdraw money: 800.0
The remaining balance is: 0.0
Savers 3 Deposit 800.0
Account balance is: 800.0
Withdraw money to withdraw money: 800.0
The remaining balance is: 0.0
Savers 1 Deposit 800.0
Account balance is: 800.0
Withdraw money to withdraw money: 800.0
The remaining balance is: 0.0

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.