代码如下
public class InterprocessLock {
public static int a = 0;
public static void main(String[] args) {
//motate50
for (int i = 0; i < 1000000; i++) {
new Thread(new TestThread(i)).start();
}
System.out.println(a);
}
static class TestThread implements Runnable {
int Flag;
public TestThread(int Flag){
this.Flag=Flag;
}
@Override
public synchronized void run() {
a++;
System.out.println(""+Flag+"|||||"+a);
}
}
}
无论是这样加
public synchronized void run() {
a++;
System.out.println(""+Flag+"|||||"+a);
}
还是这样加
public void run() {
synchronized(this) {
a++;
System.out.println("" + Flag + "|||||" + a);
}
}
结果都不正确,只有对类加锁结果正确:
public void run() {
synchronized(TestThread.class) {
a++;
System.out.println("" + Flag + "|||||" + a);
}
}