持有成员的Singleton模式中的线程安全

问题描述 投票:0回答:1

我有带有Singleton模式的此示例代码:

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中调用的方法getCountsetCount是线程安全的,不是吗?

java multithreading synchronized happens-before
1个回答
0
投票

在两个线程t1中调用的方法getCount / setCount,t2是线程安全的,不是吗?

© www.soinside.com 2019 - 2024. All rights reserved.