java--thread Synchronization

Source: Internet
Author: User

java--thread synchronization After yesterday's thread introduction, today I put the thread in the synchronization problem summed up, and now to discuss with you. What is the use of line Cheng? For example: You now have 30000 pieces of ocean in the bank, now you go to the bank to withdraw money, when you enter the password to complete, has entered the withdrawal amount, for example, you enter the 20000, is in the bank to give you money this moment, your wife also went to the bank to take the money, your wife took 20000, Because at this point your account is still 30000, so the bank of the same operation at your wife's end has been carried out, so that when you two completed their operations, the bank recorded in your account should also have 10000 of the deposit, so it is not very cool. To solve this problem, we use the knowledge of thread Cheng, let's learn it together. One, an example of unhandled thread synchronization: Public classTextsyncImplementsrunnable{/**Unhandled thread synchronization *@paramargs*/ Time Time=NewTime ();  Public Static voidMain (string[] args) {Textsync text=NewTextsync (); Thread T1=NewThread (text); Thread T2=NewThread (text); T1.setname ("T1"); T2.setname ("T2");        T1.start ();    T2.start (); } @Override Public voidrun () {Time.add (Thread.CurrentThread (). GetName ()); }}classTime {Private Static intnum = 0;  Public voidAdd (String name) {Try{num++; //when the first thread executes to this point, Num becomes 1, the first thread pauses for one second,//The second thread starts executing, and when the second thread executes to this point, Num becomes 2, and the second thread pauses for one second,//the first thread at this time Num also becomes 2, so the final result is 2;Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Name+ "is the" +num+ "thread that executes. "); }} output: Two, thread synchronization Public classTextsynctwoImplementsrunnable{/**Thread Synchronization *@paramargs*/Time1 Time=NewTime1 ();  Public Static voidMain (string[] args) {textsynctwo text=NewTextsynctwo (); Thread T1=NewThread (text); Thread T2=NewThread (text); T1.setname ("T1"); T2.setname ("T2");        T1.start ();    T2.start (); } @Override Public voidrun () {Time.add (Thread.CurrentThread (). GetName ()); }}classTime1 {Private Static intnum = 0; //synchronized locks the current thread, can be declared when a method is defined, or set in a method.      Public synchronized voidAdd (String name) {//synchronized (this) {//locks the current thread, preventing it from being executed by another thread at this time            Try{num++; Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Name+ "is the" +num+ "thread that executes. "); //}}} Output: Three, deadlock Public classTestdeadlockImplementsrunnable{/**dead Lock *@paramargs*/    Private intFlag = 0 ; StaticObject O1 =NewObject (); StaticObject O2 =NewObject ();  Public Static voidMain (string[] args) {Testdeadlock TD1=NewTestdeadlock (); Testdeadlock TD2=NewTestdeadlock (); Td1.flag= 1; Td2.flag= 2; Thread T1=NewThread (TD1); Thread T2=NewThread (TD2); T1.setname ("T1"); T2.setname ("T2");        T1.start ();    T2.start (); } @Override Public voidrun () {System.out.println (Thread.CurrentThread (). GetName ()); if(Flag = = 1){            synchronized(O1) {Try{Thread.Sleep (5000); } Catch(interruptedexception e) {e.printstacktrace (); }                synchronized(O2) {System.out.println ("1"); }            }        }        if(Flag = = 2){            synchronized(O2) {Try{Thread.Sleep (5000); } Catch(interruptedexception e) {e.printstacktrace (); }                synchronized(O1) {System.out.println ("2"); }}}} four, lock Public classTtImplementsrunnable{/**Lock *@paramargs*/    intb = 100;  Public Static voidMain (string[] args) {TT TT=NewTT (); Thread th=NewThread (TT);        Th.start (); Try{tt.m2 (); } Catch(Exception e) {e.printstacktrace ();    } System.out.println (tt.b); } @Override Public voidrun () {Try{M1 (); } Catch(Exception e) {e.printstacktrace (); }    }        Private synchronized voidM1 ()throwsexception{b= 1000; Thread.Sleep (5000); System.out.println ("B=" +b); }    Private synchronized voidM2 ()throwsexception{Thread.Sleep (2500); b= 2500; }} for locking this I have a question, but also hope that the great God to give guidance, now the output: I want to ask is, ask what M2 first execution, M1 to wait until M2 execution finished. I hope you will give us a reply.
Http://www.cnblogs.com/AndroidJotting/p/3937019.html

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.