关于java多线程中synchronized锁住的对象的问题
在一个synchronized块中锁的是this对象,另一个synchronized块中锁的是this对象中的一个属性,为什么这两个synchronized块是异步执行的呢
如果当前拿到了this的锁,在其他线程中拿到了this的属性的锁,并对这个属性进行了修改,那岂不是就是对this对象作出了修改?
class Service {
private String anyString = new String();
public void a() throws InterruptedException {
synchronized (anyString) {
System.out.println("a begin");
Thread.sleep(3000);
System.out.println("a end");
}
}
public void b() {
synchronized (this) {
System.out.println("b begin");
System.out.println("b end");
}
}
}
class ThreadA implements Runnable {
private Service service;
public ThreadA(Service service) {
this.service = service;
} @Override public void run() {
try {
service.a();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class ThreadB implements Runnable {
private Service service;
public ThreadB(Service service) {
this.service = service;
} @Override public void run() {
service.b();
}
}
public class Main {
public static void main(String[] args) {
Service service = new Service();
new Thread(new ThreadA(service)).start();
new Thread(new ThreadB(service)).start();
}
}
最终输出结果: 我认为应该是:
a begin
a end
b begin
b end
求大佬解答!!!
#Java##笔试题目#