题目:
两个线程thread1、thread2,一个Test的实例test,thread1访问test.getFirst()、thread2访问test.getSecond()。问题:能不能同时访问,并解释原因。
public class Test {
private volatile int first;
private static int second;
public sychronized int getFirst(){
return first;
}
public sychronized int getSecond(){
return second;
}
}
答案:
不能同时访问,synchronized关键字用在方法上,锁住的是该方法的所属对象,同一时间对象锁只能被一个线程获取,其他线程只能等待锁释放