Java thread Synchronization

Source: Internet
Author: User

With regard to thread security, here's a very simple question for the bank to withdraw money:

    • User input account, password, system to determine whether the match
    • User input amount to withdraw money
    • The system determines whether the amount of money is reasonable and whether it is greater than the balance
    • If the amount of money taken is less than or equal to the balance, the money is successful.

When two users use the same account to withdraw money, the equivalent of two threads and take the money, there may be an error.

The error occurs because the run () method does not have synchronization security. To solve this problem, Java multithreading supports the introduction of synchronization monitors, using the format of the synchronization monitor as follows:

Sysnchronized (BoJ) {

..........

}

Its operating logic is: locking > Modify > Release lock

Synchronized keywords can be decorated with methods, code blocks, cannot decorate constructors, member variables

The synchronization Monitor is released in the following situations:

    1. The synchronization method of the current thread of execution or the end of the synchronization code block execution
    2. The synchronization method of the current thread of execution or the synchronization code encountered Break,return terminated the method or block of code
    3. The wait () method that executes the synchronization monitor object in a program that currently executes the thread's synchronization method or synchronizes the code

The synchronization monitor is not released in the following scenarios

    1. When a thread executes a synchronous method or synchronizes a block of code, the program calls the Thread.Sleep (), Thread.yield () method
    2. When a thread executes a code block, other threads execute the thread's suspend () method to suspend the thread

Here's a small example of a bank taking money:

 Packagecom.tc.test; Public classacount {PrivateString Accountno; Private Doublebalance;  PublicAcount (String Accountno,Doublebalance) {        Super();  This. Accountno =Accountno;  This. Balance =balance; }         PublicString Getaccountno () {returnAccountno; }     Public voidSetaccountno (String accountno) { This. Accountno =Accountno; }     Public DoubleGetBalance () {returnbalance; }//Public void Setbalance (double balance) {//this.balance = balance;//    }     Public synchronized voidDrawDoubleDrawamount) {        if(Balance >Drawamount) {System.out.println (Thread.CurrentThread (). GetName ()+ "Win Money" +drawamount); Try{Thread.Sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); }            //Modify Balancebalance-=Drawamount; System.out.println ("Balance is:" +balance); }Else{System.out.println ("Failed to withdraw money, insufficient balance!!!" "); }    }}
 Packagecom.tc.test; Public classDrawthreadextendsThread {Privateacount account; Private DoubleDrawamount;  PublicDrawthread (String name, acount account,DoubleDrawamount) {        Super(name);  This. Account =Account ;  This. Drawamount =Drawamount; }     Public voidrun () {Account.draw (drawamount); }    }
 Package com.tc.test;  Public class drawtest {    publicstaticvoid  main (string[] args) {            acount ac= New Acount ("123", +);             New Drawthread ("First", ac,800). Start ();             New Drawthread ("Second", ac,800). Start ();    }}

Sync Lock

Starting with jdk1.5, Java provides a more powerful mechanism for thread synchronization ———— synchronization is achieved by displaying the definition of a synchronization lock object, in which the lock object acts as a synchronous locking mechanism.

Lock is a tool that controls access to a shared resource by a thread, usually with a lock providing exclusive access to a shared resource, and only one thread at a time locks the lock, and the thread must first obtain the lock object before accessing the shared resource

Java8 has added a new type of Stampedlock class that provides three lock modes for reading and writing: Writing,readoptimistic,reading.

Dead lock

When two threads wait for each other to release the Sync Monitor, a deadlock occurs, the Java Virtual machine does not detect, and no action is taken to handle the deadlock, and in the event of a deadlock, no exception occurs for the entire program, and there is no hint, except that all threads are in a blocking state.

Java thread 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.