Communication for Java multi-thread threads

Source: Internet
Author: User

Communication for Java multi-thread threads

Before summarizing the multithreading communication, introduce a concept: lock pool. The blocking that occurs because the thread did not get the lock tag is different from the block in the previous five basic states, called the lock pool. Each object has its own pool of locks, which is used to place the thread waiting to run. Which thread in these threads gets the lock tag is determined by the system. In the front we also have the concept of T to deadlock, where threads wait for other threads to release the lock tag without releasing their own, causing endless waiting. When a deadlock occurs, how do we solve it? Resolved through communication between threads.

    • Inter-thread communication:
There are 2 ways to communicate between multithreading, the first is to use several methods of the object class, and the second is to control coordination by changing the conditions of use. Here we highlight the first type of
1, the Inter-thread communication mechanism is actually the coordination mechanism. The space used by inter-thread communication is called the waiting queue of an object, and this queue is also the object's space. It is worth noting that an object, in addition to attributes and methods, has a mutex tag, a lock pool space, and a waiting queue space.
2,wait () Method: Causes the current thread to wait
3,notify () method: Wakes a thread above this synchronization monitor.
4,notifyall () Method: Wakes all threads above this synchronization monitor.
    • It is worth noting that:
1, Wait () and notify () are only available for locked resources (synchronized method).
2, we should replace notify with Notifyall, because we use notify to release a thread that is indeterminate and is determined by the OS.
3, Release the lock tag only at the end of the synchronized code or call Wait ().
4. The lock mark is self-releasing and must be notified.
5, in the program to determine whether a condition is set up to pay attention to using while is more stringent than using if.


The following code simulates a deposit and withdrawal logic, with the following code:

/** * * @version 1L * @author linkinpark * @since 2015-2-5 * @motto dream like fireworks heart like water, classmate teenager not romance * @desc ^ later in the code to develop good habits, if a If some properties of the class cannot be changed casually, do not provide the Set method */public class Account{private String accountno;//account number private double balance;//account balance Private Boolean flag = false;//identifies whether a deposit is already in the account in the flag public accounts () {}public (String Accountno, double balance) {This.accountno = Accountno;this.balance = balance;} public void Setaccountno (String accountno) {this.accountno = Accountno;} Public String Getaccountno () {return this.accountno;} Therefore, the account balance is not allowed to be arbitrarily modified, so only for balance to provide getter method, do not provide the Set method public double GetBalance () {return this.balance;} Public synchronized void Draw (double drawamount) {try{//If flag is false, no one in the account has been saved in, the method of taking money blocks if (!flag) {wait ();} else{//executes the money System.out.println (Thread.CurrentThread (). GetName () + "withdraw money:" + drawamount); balance-= Drawamount; System.out.println ("Account balance:" + balance);//The flag that identifies whether the account has a deposit is set to false. Flag = false;//Wakes other threads Notifyall ();}} catch (Interruptedexception ex) {ex.printstacktrace ();}} Public synchronized void deposit (Double depositamount) {try{//If the flag is true, indicating that someone has saved money in the account, the method of saving is blocked if (flag) {Wait ();} else{//Execution Deposit System.out.println (Thread.CurrentThread () getName () + "deposit:" + depositamount); balance + = Depositamount; System.out.println ("Account balance:" + balance);//will indicate whether the account has a deposit flag set to Trueflag = true;//Wake up Other Threads Notifyall ();}} catch (Interruptedexception ex) {ex.printstacktrace ();}} The following two methods override the Hashcode () and Equals () methods according to accountno 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;}}

/** *  * @version 1L * @author linkinpark * @since 2015-2-5 * @motto dream like fireworks heart like water, classmate teenager not romance * @desc ^  Take the money thread */public class Drawthread extends Thread{private account account;//demo user accounts private double drawamount;//The amount of money the current fetch thread wants to take public drawthread ( String name, account account, double drawamount) {super (name); this.account = Account;this.drawamount = Drawamount;} Repeat 100 execution take money operation public void Run () {for (int i = 0; i < i++) {Account.draw (Drawamount);}}}

/** * @version 1L * @author linkinpark * @since 2015-2-5 * @motto dream like fireworks heart like water, classmate teenager not romance * @desc ^ saving thread */public class Depositthr EAD extends Thread{private account account;//demo user accounts private double depositamount;//The amount of money the current fetch thread wants to deposit public depositthread ( String name, account account, double depositamount) {super (name); this.account = Account;this.depositamount = Depositamount;} Repeat 100 times execution deposit operation public void Run () {for (int i = 0; i < i++) {account.deposit (Depositamount);}}}

public class Drawtest{public static void Main (string[] args) {//Create an account accounts acct = new ("Nightwish", 0); new DRAWT Hread ("Money-ACCT"). Start (); New Depositthread ("Depositor a", acct, +). Start (); New Depositthread ("Depositor B", acct, 800). Start (); New Depositthread ("Depositor C", acct, +). Start ();}}


About the 2nd way, it's good to know. I went through the API, which is how to introduce condition. Condition the object monitor method (wait, notify, and Notifyall) into distinct objects to provide multiple wait set (Wait-set) for each object by combining these objects with any Lock implementation. Where Lock replaces the use of the Synchronized method and the statement, Condition replaces the use of the Object monitor method. This approach is used with the previous lock lock, lock generally uses reentrantlock to do the implementation class, there are lock and UNLOCK2 lock and Release lock method, here condition by the lock Newcondition () method obtained, Then there is a Await,signal,signalall3 method is relatively simple, here do not repeat.

Communication for Java multi-thread 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.