java--thread Synchronization

Source: Internet
Author: User

Following yesterday's thread introduction, today I have the thread in the synchronization problem summed up a bit, 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 class Textsync implements runnable{    /** unhandled thread synchronization     * @param args *     /time Time    = new Time ();    public static void Main (string[] args) {        Textsync text = new Textsync ();        thread T1 = new thread (text);        Thread t2 = new Thread (text);        T1.setname ("T1");        T2.setname ("T2");        T1.start ();        T2.start ();    }    @Override public    Void Run () {        time.add (Thread.CurrentThread (). GetName ());}    } Class Time {    private static int num = 0;    public void Add (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 begins execution, when the second thread executes to this point, Num becomes 2, 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 (+            );        } catch (Interruptedexception e) {            e.printstacktrace ();        }        System.out.println (name+ "is the" +num+ "thread that executes. ");    }}

Output Result:

Second, thread synchronization

public class Textsynctwo implements runnable{    /** thread synchronization     * @param args     *    /Time1 time = new Time1 ();    public static void Main (string[] args) {        textsynctwo text = new Textsynctwo ();        thread T1 = new thread (text);        Thread t2 = new Thread (text);        T1.setname ("T1");        T2.setname ("T2");        T1.start ();        T2.start ();    }    @Override public    Void Run () {        time.add (Thread.CurrentThread (). GetName ());}    } Class Time1 {    private static int num = 0;        Synchronized locks the current thread, can be declared when a method is defined, or set in a method. Public    synchronized void Add (String name) {        //synchronized (this) {//locks the current thread, preventing the other thread from executing the            try {                num ++;                Thread.Sleep (+);            } catch (Interruptedexception e) {                e.printstacktrace ();            }            System.out.println (name+ "is the" +num+ "thread that executes. ");        //}    }}

Output Result:

Third, deadlock

public class Testdeadlock implements runnable{/** deadlock * @param args */private int flag = 0;    Static Object O1 = new Object ();    Static object O2 = new Object ();         public static void Main (string[] args) {Testdeadlock TD1 = new Testdeadlock ();         Testdeadlock TD2 = new Testdeadlock ();        Td1.flag = 1;        Td2.flag = 2;         thread T1 = new Thread (TD1);        Thread t2 = new Thread (TD2);        T1.setname ("T1");        T2.setname ("T2");        T1.start ();    T2.start ();        } @Override public void Run () {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 class TT implements runnable{    /** lock     * @param args */    int b = +;    public static void Main (string[] args) {        tt TT = new TT ();        Thread th = new thread (TT);        Th.start ();        try {            tt.m2 ();        } catch (Exception e) {            e.printstacktrace ();        }        System.out.println (tt.b);    }    @Override public    Void Run () {        try {            m1 ();        } catch (Exception e) {            e.printstacktrace ();        }    }        Private synchronized void M1 () throws exception{        B = +;        Thread.Sleep (the);        System.out.println ("b=" +b);    Private synchronized void M2 () throws exception{        Thread.Sleep (2500);        b = 2500;    } }

I have a question about locking this, and I look to the gods for guidance, now the output:

What I want to ask is, ask what M2 first executes, M1 to wait for M2 execution to finish the rear executable.

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.