【发布时间】:2018-09-02 13:10:58
【问题描述】:
我有两个线程可以访问一个对象。使用同步(a),我在对象a上提供锁,所以现在每次线程都可以访问对象“a”并修改它。如果执行此代码,我们有1 2。有时没有同步块我们得到2 2。(线程 t1 获得 i 并增加 i 现在线程 t2 获得 i 并增加线程 t1 获得 i 并打印 2,线程 t2 获得 i 并打印 2) 如果我是真的,为什么我们不能使用 synchronized(this) 而不是 synchronized(a)?
public class Foo {
public static void main(String[] args) {
B b =new B();
b.start();
}
}
class B{
A a = new A();
Thread t1 =new Thread(new Runnable(){
public void run(){
synchronized(a){
a.increment();
}
}
});
Thread t2 =new Thread(new Runnable(){
public void run(){
synchronized(a){
a.increment();
}
}
});
public void start(){
t1.start();
t2.start();
}
}
class A{
int i = 0;
public void increment() {
i++;
System.out.println(i);
}
}
【问题讨论】:
标签: java multithreading synchronized-block