spring单例是线程保险的吗
spring单例是线程安全的吗?
我写一段代码来验证:
通过输出的结果来是:每个线程都输出了0~9,应该是线程安全的,但我不知道我这个测试逻辑上是否是正确的,
,谁能给个详细的解答?
我写一段代码来验证:
public class Singleton { int m=-1; private Singleton() { m=0; } private static Singleton instance = new Singleton(); public static Singleton getInstance() { return instance; } public static void main(String[] args){ Singleton single=Singleton.getInstance(); NewThread t1=new NewThread(); NewThread t2=new NewThread(); NewThread t3=new NewThread(); t1.setSingle(single); t2.setSingle(single); t3.setSingle(single); t1.start(); t2.start(); t3.start(); } } class NewThread extends Thread{ private Singleton single; public void setSingle(Singleton single) { this.single = single; } @Override public void run() { // TODO Auto-generated method stub super.run(); for(int i=1;i<10;i++){ single.m=i; System.out.println("current thread:"+Thread.currentThread()+"current m:"+single.m); } } }
通过输出的结果来是:每个线程都输出了0~9,应该是线程安全的,但我不知道我这个测试逻辑上是否是正确的,