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

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

作者: 联想桥南 | 来源:发表于2022-01-08 10:22 被阅读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;
    }
    

    }

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/waqecrtx.html