//饿汉式线程安全——单例模式
public class Singleton {
//定义本类的一个私有实例对象
private static volatile Singleton single = null;
//私有化构造
private Singleton() {}
//因为不能创建对象,对外提供静态方法
public static Singleton getSingleton() {
if(single == null) {//先判断是否创建该类的单例对象single
synchronized(Singleton.class) {
/*可能多个线程都同时进行第一层if判断在锁外面等待,当一个线程创建完成释放锁后,
* 如果不加判断则会导致再次创建对象
*/
if(single == null) {
single = new Singleton();
}
}
}
return single;
}
}
2.多线程实现两个线程交替打印20以内的数
//线程交替打印
public class ThreadPrint {
public static void main(String[] args) {
ThreadCase one = new ThreadCase();
Thread t1 = new Thread(one);
Thread t2 = new Thread(one);
t1.