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)