Java Multithreaded Learning-synchronization (synchronized)

Source: Internet
Author: User

(examples are on-line video)

If two threads call a method output string at the same time

 Public classSynchronizedtestextendsThread { Public Static voidMain (string[] args) {FinalSynchronizedtest st =Newsynchronizedtest (); NewThread (NewRunnable () { Public voidrun () { while(true){                    Try{Thread.Sleep (10); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } st.outputstr ("This is test");        }}). Start (); NewThread (NewRunnable () { Public voidrun () { while(true){                    Try{Thread.Sleep (10); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } st.outputstr ("Okokokokokok");    }}). Start (); }             Public voidoutputstr (String str) { for(intI=0;i<str.length (); i++) {System.out.print (Str.charat (i));    } System.out.println (); }}

Output:

This is test
Okokokokokok
This is test
Okokokokokok
This is test
Okokothis is test
Kokokok
Tokokokokokok
He is test
Okokokokokok
This is test
Okokthisokokokok
is test
Okothkoiskokokok
is test
Okokokothis is test
Kokok
This Iokokokokokok
S test
Okokokothiskokok
is test
Okokokokokokthis
is test
Okthisok is Tokokokoest

It can be seen that at the beginning of the output is not a problem, and then the output is chaotic.

The workaround is to add the synchronization method to the Outputstr method to add the Sync keyword synchronized can

     Public synchronized void outputstr (String str) {        for (int i=0;i<str.length ();i++) {            System.out.print (Str.charat (i));        System.out.println ();    }

Synchronized:

The Java language keyword, which can be used to lock objects and methods or blocks of code, when it locks a method or a block of code, at most one thread at a time executes the code. When two concurrent threads access the same object in the same lock synchronization code block, only one thread can be executed within a single time. The other thread must wait for the current thread to finish executing the block before it can execute the code block. However, when a thread accesses one of the lock code blocks of object, another thread can still access the non-locking code block in the object.

Of course, synchronized can be used not only on the method, but also on the object.

1. Use on string

 Public classSynchronizedTest2 { Public Static voidMain (string[] args) {FinalSynchronizedTest2 t2 =NewSynchronizedTest2 (); NewThread (NewRunnable () { Public voidrun () { while(true){                    Try{Thread.Sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } t2.outputstr ("Thread-1");                }}). Start (); NewThread (NewRunnable () { Public voidrun () { while(true){                    Try{Thread.Sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } t2.outputstr ("Thread-2");    }}). Start (); }         Public voidoutputstr (String threadname) {string str= "123"; synchronized(str) {Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (ThreadName+ "-" +system.currenttimemillis ()/1000); }    }}

Output:

Thread-1-1475373023
Thread-2-1475373024
Thread-1-1475373025
Thread-2-1475373026
Thread-1-1475373027

As can be seen, every second only one thread is running, but also do not feel is thread-1 run under, thread-2 Run, random. Synchronization of strings is also possible, but synchronization must be the same object in order to be mutually exclusive.

Such as: Change the Outputstr method to
 Public void outputstr (String threadname) {        = "123";         synchronized (threadname) {            try  {                thread.sleep ();             Catch (interruptedexception e) {                e.printstacktrace ();            }             + "-" +system.currenttimemillis ()/1000);        }    }

This time the synchronized is in sync with the ThreadName parameter.

Output:

Thread-1-1475373333
Thread-2-1475373333
Thread-1-1475373334
Thread-2-1475373334
Thread-1-1475373335
Thread-2-1475373335
Thread-1-1475373336
Thread-2-1475373336

You can see that two threads are running in the same second, and there are no mutexes in two threads.

2. Use on thisChange the Outputstr method to
 Public void outputstr (String threadname) {        = "123";         synchronized (this) {            try  {                thread.sleep ();             Catch (interruptedexception e) {                e.printstacktrace ();            }             + "-" +system.currenttimemillis ()/1000);        }    }

The thread that invokes the same SynchronizedTest2 object is mutually exclusive in this method.

But if we change the main method to this,

 Public classSynchronizedTest2 { Public Static voidMain (string[] args) {NewThread (NewRunnable () { Public voidrun () {SynchronizedTest2 t2=NewSynchronizedTest2 ();  while(true){                    Try{Thread.Sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } t2.outputstr ("Thread-1");                }}). Start (); NewThread (NewRunnable () { Public voidrun () {SynchronizedTest2 t2=NewSynchronizedTest2 ();  while(true){                    Try{Thread.Sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); } t2.outputstr ("Thread-2");    }}). Start (); }         Public voidoutputstr (String threadname) {string str= "123"; synchronized( This){            Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (ThreadName+ "-" +system.currenttimemillis ()/1000); }    }}

That is, each thread uses a different SynchronizedTest2 object, and the output is:

Thread-2-1475376542
Thread-1-1475376542
Thread-1-1475376543
Thread-2-1475376543
Thread-1-1475376544
Thread-2-1475376544
Thread-1-1475376545
Thread-2-1475376545

You can see that two threads are not mutually exclusive at this time. So synchronizing this will only be mutually exclusive if the same object is used.

3. Use the byte code on the class

Change the Outputstr method to

 Public void outputstr (String threadname) {        = "123";         synchronized (SynchronizedTest2. class {            try  {                thread.sleep ();             Catch (interruptedexception e) {                e.printstacktrace ();            }             + "-" +system.currenttimemillis ()/1000);        }    }

At this point, regardless of whether the two threads in the main method are using the same SynchronizedTest2 object or a different object, the method can be called mutually exclusive and not run at the same time. Probably because there is only one byte-code object.

In fact, put synchronized on the method, as if with such synchronization.

Synchronized keyword temporarily only think so much, write a bit messy.

Java Multithreaded Learning-synchronization (synchronized)

Related Article

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.