假如synchronized了一个对象,而这个对象的成员变量中有另个对象的引用,那么是否同时锁住了那个引用所指的对象?
A对象中有对象C的引用,synchronized(this)锁住了A,那么另个调用了对象C的线程还能继续执行吗?
测试是可以的,但是不能保证测试代码是正确的。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class A implements Runnable{
C c;
A(C test){
c = test;
}
@Override
public void run() {
// TODO Auto-generated method stub
synchronized(this){
while(true){
c.test = 1;
System.out.println(c.test);
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
class C implements Runnable{
int test = 0;
@Override
public void run() {
// TODO Auto-generated method stub
synchronized(this){
while(true){
System.out.println(0);
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class TestScope {
public static void main(String[] args) {
// TODO Auto-generated method stub
C c = new C();
A a = new A(c);
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(a);
exec.execute(c);
}
}
运行部分结果
1
0
0
1
1
0
1
0
1
0
0
1
1
0
1
0
1
0