美文网首页
多线程先输出2再输出1

多线程先输出2再输出1

作者: YAOPRINCESS | 来源:发表于2020-09-16 11:01 被阅读0次

    wait/notify

    package com.kang.multithread;
    
    /**
     * @author klr
     * @create 2020-09-16-10:53
     */
    public class Print21 {
    
        static final Object lock = new Object();
        static boolean con = false;
    
        public static void main(String[] args) {
            new Thread(()->{
                synchronized (lock) {
                    while (!con) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(1);
                }
    
            },"t1").start();
    
            new Thread(()->{
                synchronized (lock) {
                    System.out.println(2);
                    con = true;
                    lock.notify();
                }
            },"t2").start();
        }
    }
    

    park/unpark

    package com.kang.multithread;
    
    import java.util.concurrent.locks.LockSupport;
    
    /**
     * @author klr
     * @create 2020-09-16-10:53
     */
    public class Print21 {
    
        static final Object lock = new Object();
        static boolean con = false;
    
        public static void main(String[] args) {
            Thread t1 = new Thread(() -> {
    //            synchronized (lock) {
    //                while (!con) {
    //                    try {
    //                        lock.wait();
    //                    } catch (InterruptedException e) {
    //                        e.printStackTrace();
    //                    }
    //                }
                LockSupport.park();
                System.out.println(1);
    //            }
    
            }, "t1");
            t1.start();
    
            new Thread(()->{
    //            synchronized (lock) {
    //                System.out.println(2);
    //                con = true;
    //                lock.notify();
    //            }
                System.out.println(2);
                LockSupport.unpark(t1);
            },"t2").start();
        }
    }
    

    相关文章

      网友评论

          本文标题:多线程先输出2再输出1

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