Java Concurrency Programming (i)

Source: Internet
Author: User

A problem may occur when multiple threads access the same variable . Here I use two threads to access an int count variable at the same time, so that they are at the same time +1. At the same time let the thread sleep 1 seconds, each thread executes 10 times, finally should output 20 is right, because count++ is not atomic operation, here need to do concurrency, such as with Syn ... What keywords, of course, there are other ways. Back there.

Here in order to be two threads access is the same variable i used static variable private static int count = 1

Thread1 Threading Class

1  PackageCom.gxf.thread;2 3  Public classThread1extendsThread {4     Private Static intCount = 1;5 6     7 @Override8      Public voidrun () {9         Super. Run ();Ten          for(inti = 0; I < 10; i++){ OneSystem.out.println ("in Thread count =" + count++); A             Try { -Sleep (1000); -}Catch(interruptedexception e) { the                 //TODO auto-generated Catch block - e.printstacktrace (); -             } -         } +     } -  +}

Test.java Test class

1  PackageCom.gxf.thread;2 3  Public classTest {4 5      Public Static voidMain (string[] args) {6Thread Thread1 =NewThread1 ();7         8Thread thread2 =NewThread1 ();9     Ten          One Thread1.start (); A Thread2.start (); -     } -  the}

From the above you can see that there are two 15, indicating that there is a problem in the middle of 14 to 15 or 13 to 14, which is a thread safety issue

Java Concurrency Programming (i)

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.