Oracle的教程Intrinsic Locks and Synchronization说:
Intrinsic[Monitor] locks play a role in both aspects of synchronization: enforcing exclusive access to an object’s state
我假设如果一个线程正在执行“同步”方法,则一个对象中的任何值都不能同时被两个线程操纵.
因此,当以下代码具有以下输出时,我感到很惊讶(尽管出于我想要做的目的而松了一口气).我不太确定会发生什么,但是我发现有错误或可能会发生某些情况.
据我了解,如果另一个线程正在请求该对象的监视状态,则“同步”仅用于限制对该对象的访问,但如果另一个线程正在更改一个值,则不会.这个对吗?
public class HelloWorld implements Runnable{
Thread t1;
Thread t2;
int val1 = 0;
int val2 = 0;
public static void main(String[] args) {
HelloWorld h1 = new HelloWorld();
h1.t1 = new Thread(h1);
h1.t2 = new Thread(h1);
h1.t1.start();
h1.t2.start();
}
@Override
public void run() {
System.out.println("STARTED");
System.gc();
Thread currentThread = Thread.currentThread();
if (currentThread == this.t1) {
this.locker(); //This is a synchronized method, incrementing val1
}
if (currentThread == this.t2) {
this.adder(); //This is a non-synchronized method, incrementing val2
}
}
private synchronized void locker() {
for(int i = 0; i < 3; i++){
val1++;
System.out.println("LOCKER: " + this.val1);
}
}
private void adder() {
while(this.val2 < 3) {
this.val2++;
System.out.println("ADDER: " + this.val2);
}
synchronized(this) {
//Synchronize for final output
System.out.println("FINAL");
System.out.println(val1);
System.out.println(val2);
}
}
}
STARTED
STARTED
ADDER: 1
LOCKER: 1
LOCKER: 2
ADDER: 2
LOCKER: 3
ADDER: 3
FINAL
3
3