多线程的一些例子,多线程循环打印A和B,单例模式double c

2022-01-08  本文已影响0人  联想桥南

多线程循环打印A&B

public class MultiThreadPrint {

    private static ReentrantLock lock = new ReentrantLock();
    private static Condition conditionA = lock.newCondition();
    private static Condition conditionB = lock.newCondition();

    static void printA() {
        for(int i = 0; i< 1000; i++){
            try {
                lock.lock();
                System.out.println("print A");
                //synchronize使用wait notify阻塞和唤醒,lock使用await&signal
                conditionB.signal();
                conditionA.await();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }

    static void printB() {
        for (int i = 0; i < 1000; i++){
            try {
                lock.lock();
                System.out.println("print B");
                conditionA.signal();
                conditionB.await();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        new Thread(() -> {
            printA();
        }).start();
        new Thread(() -> {
            printB();
        }).start();
    }

单例模式-静态内部类
public class Singleton {

//私有构造方法
private Singleton() {
}

//静态内部类能保证没被调用时,不被初始化
private static class SingletonInner {
    private static final Singleton singleton = new Singleton();
}

//线程安全
public static Singleton getSingleton() {
    return SingletonInner.singleton;
}

}


双重校验

public class Singleton {

//私有构造方法
private Singleton() {
}

// volatile防止指令重排
private static volatile Singleton singleton = null;

public static Singleton getSingleton() {
    //double-check
    if(singleton == null){
        synchronized(Singleton.class){
            if(singleton == null){
                singleton = new Singleton();
            }
        }
    }
    return singleton;
}

}

上一篇下一篇

猜你喜欢

热点阅读