我有这个带有单例模式的示例代码:
class Singleton{
private static Singleton instance;
private int count;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(instance==null){
instance=new Singleton();
}
return instance;
}
public int getCount(){return count;}
public void setCount(int count){this.count=count;}
public static void main(String[] args) throws InterruptedException{
Thread t1=new Thread(()->{
while(Singleton.getInstance().getCount()==0){
//loop
}
System.out.println("exist t1 with count="+Singleton.getInstance().getCount());
});
t1.start();
Thread.sleep(1000); //time out to force t1 start before t2
Thread t2=new Thread(()->{
Singleton.getInstance().setCount(10000);
});
t2.start();
t1.join();
t2.join();
}
}
我有一个问题:在两个线程 t1、t2 中调用的方法getCount
和setCount
哪个是线程安全的,不是吗?