【Java】懒汉式多线程安全问题

public class Test {
    public static void main(String[] args) {
        for (int i=0;i<600;i++) {
            new Thread(T.getInstance()).start();
        }
    }
}

class T implements Runnable {
    private static T t = null;
    private T() {}
    public static T getInstance() {
        if (t==null) {
            return t = new T();
        }
        return t;
    }
    public synchronized void run() {
        System.out.println(Thread.currentThread().getName()+"\t"+T.getInstance());
        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 

posted @ 2019-09-18 16:51  自清闲  阅读(18)  评论(0)    收藏  举报