Java Multithreading (v) multi-threaded synchronization

Source: Internet
Author: User

Java Multithreading (v) multi-threaded synchronization

why to introduce a synchronization mechanism

  In a multithreaded environment, there could be two or more threads trying to access a limited resource at the same time. This potential resource conflict must be prevented.

  workaround : locking the thread when using a resource.

  after the first thread that accesses the resource adds a lock to it, the other thread can no longer use that resource unless it is unlocked .

Program Examples

Use a money-fetching program example to explain why you need to introduce synchronization.

Before using the synchronization mechanism, the overall program is as follows:

 

Public classfetchmoneytest{Public static voidMain (string[] args) {Bank Bank =NewBank (); Thread T1 =NewMoneythread (Bank);//withdraw money from banks Thread t2 =NewMoneythread (Bank);//Withdraw money from the teller Machine T1.start ();    T2.start (); }}classbank{private intMoney = 1000;public intGetmoney (int number) {if(Number < 0) {return-1; }else if(Number > Money) {return-2; }else if(Money < 0) {return-3; }Else{Try{thread.sleep (1000); }Catch(Interruptedexception e)            {E.printstacktrace ();            } Money-= number; System. out. println ("Left money:" + money);returnNumber }    }}classMoneythreadextends Thread {PrivateBank Bank; PublicMoneythread (Bank Bank) { This. Bank = Bank; } @OverridePublic voidRun () {System. out. println (Bank.getmoney (800)); }}

The program defines a bank class, which contains the user's stored money (1000 yuan), and then use two threads for the money operation, you can see that although the Bank class of the Getmoney () method to the amount of money and deposit data to judge, but after execution, the results output two 800, Indicates that 800 dollars have been successfully removed from two threads.

  What is this for? because there are some logical judgments in the Getmoney () method, after entering the last else statement block, there is a brief hibernation, and the second thread successfully enters the else block (because the deposit money hasn't been taken away) during the first thread's hibernation. When two threads end sleep, no longer logical judgment but directly take the money away, so two threads have taken 800 yuan, when money is negative 600.

Note that it is not possible to determine which thread is the first thread, which thread is the second thread, and the order is indeterminate.

In the Getmoney () method, add the Print statement output the remaining amount of money, you can see the output for the remaining amount of 200,-600, or -600,-600. This is not necessarily because another thread may have not taken the money away or may have taken it before the first output of the remaining amount.

Solutions

  workaround : Add the keyword synchronizedon the Getmoney () method.

That is, after the program changes as follows: (just add a keyword)

Example of a corrected procedure

Public classfetchmoneytest{Public static voidMain (string[] args) {Bank Bank =NewBank (); Thread T1 =NewMoneythread (Bank);//withdraw money from banks Thread t2 =NewMoneythread (Bank);//Withdraw money from the teller Machine T1.start ();    T2.start (); }}classbank{private intMoney = 1000;public synchronized intGetmoney (int number) {if(Number < 0) {return-1; }else if(Number > Money) {return-2; }else if(Money < 0) {return-3; }Else{Try{thread.sleep (1000); }Catch(Interruptedexception e)            {E.printstacktrace ();            } Money-= number; System. out. println ("Left money:" + money);returnNumber }    }}classMoneythreadextendsthread{PrivateBank Bank; PublicMoneythread (Bank Bank) { This. Bank = Bank; } @OverridePublic voidRun () {System. out. println (Bank.getmoney (800)); }}
public class fetchmoneytest{public static void Main (string[] args) {Bank Bank = new Bank ();        Thread T1 = new Moneythread (bank),//withdraw money from the banks thread t2 = new Moneythread (bank);//Withdraw money from cash machine t1.start ();    T2.start ();    }}class bank{Private int money = 1000;        public synchronized int Getmoney (int number) {if (number < 0) {return-1;        } else if (number > Money) {return-2;        } else if (Money < 0) {return-3;            } else {try {thread.sleep (1000);            } catch (Interruptedexception e) {e.printstacktrace ();            } Money-= number;            System.out.println ("Left money:" + money);        return number;    }}}class Moneythread extends thread{private Bank bank;  Public Moneythread (Bank bank) {this.bank = Bank;  } @Override public void Run () {System.out.println (Bank.getmoney (800)); }}

This results in the following output:

Left money:200
800
-2

Indicates that after the first withdrawal of 800 yuan, the remaining 200 yuan, when another thread to fetch, no longer have to withdraw money.

Once a thread starts executing a method of fetching money, it blocks other threads from executing the method until the thread ends and the other threads have access rights.

  When the synchronized keyword Modifies a method, the method is called a synchronous method .

  Each object in Java has a lock , or monitor , that locks the object when a thread accesses the synchronized method of an object. No other thread can access the object's synchronized method anymore. Until the previous thread executes the method (or throws an exception), the object's lock is freed, and the other thread can then access the object's Synchronized method.

Note that this is a lock on the object, and if it is a different object, there is no restriction between the objects.

Resources

Santhiya Garden Zhang Long teacher Java SE Series video tutorial.

Source: http://www.cnblogs.com/mengdd/archive/2013/02/16/2913680.html

Java Multithreading (v) multi-threaded synchronization

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.