public class SychronizdDemo {
The static Integer count=0;
Public static void incr () {
Synchronized (count) {
Try {
Thread.sleep (1);
{} catch InterruptedException (e)
e.printStackTrace();
}
count++;
}
}
Public static void main (String [] args) throws IOException, InterruptedException {
for(int i=0; i<1000; I++) {
New Thread (() - & gt; SychronizdDemo. Incr ()). The start ();
}
Thread.sleep (5000);
System. The out. Println (" result: "+ count);
}
}
Why sleep not releases the lock and the output result is less than 1000 number???????
CodePudding user response:
Personally think that an Integer from 0-127 with Java memory address of the default, so every time after update the count, in fact, the monitor has changed not guarantee must be thread safeCodePudding user response:
Said some of the issues that should be after every + +, the count is no longer the same count, he will return again new integer, so the monitor has been changed,Is the scope of and integer cache - 128-127
CodePudding user response:
Sleep itself will not release the lock, after count++ count object has changed, so use class object lock is ok,CodePudding user response:
Upstairs, positive solutions [align=center]Lock the object has changed, you always change the Integer,
Program to which is a step in the right, which get a lock object as a lock) :
Public class SychronizdDemo {
The static Object lock=new Object ();
The static Integer count=0;
Public static void incr () {
Synchronized (lock) {
Try {
Thread.sleep (1);
{} catch InterruptedException (e)
e.printStackTrace();
}
count++;
System. The out. Println (count);
}
}
Public static void main (String [] args) throws IOException, InterruptedException {
for(int i=0; i<1000; I++) {
New Thread (() - & gt; SychronizdDemo. Incr ()). The start ();
}
Thread.sleep (5000);
System. The out. Println (" result: "+ count);
}
}
Can look at my blog: https://blog.csdn.net/Kurry4ever_/article/details/109557532