High concurrent programming series (three)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_43874301/article/details/102459667

High concurrent programming series (three)

High concurrency programming series

After notify, t1 must release the lock, after t2 exits, must notify, inform t1 continues.
the entire communications is cumbersome
using LATCH (latch) instead wait notify to notify
advantage is a process of communication is simple, but can also specify a wait time
using and await countdown method instead of the wait and the Notify
CountDownLatch does not involve locking thread continues to run when the first count value is zero.
when not involved in sync, just involving thread communication with synchronized + wait / notify becomes too important.
this You should consider countDownlatch / cyclibarrier / semaphore.

public class Tu {

    volatile List lists = new ArrayList();

    public void add(Object o) {
        lists.add(o);
    }

    public int size() {
        return lists.size();
    }

    public static void main(String[] args) {
        Ts t = new Ts();

        //一个门闩   为零时门就开了
        CountDownLatch latch = new CountDownLatch(1);

        new Thread(() -> {
                System.out.println("t2启动");
                if (t.size() != 5) {
                    try {
                        latch.await();
                        //也可以指定时间
                      //latch.await(5000,TimeUnit.MILLISECONDS);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("t2结束");
        },"t2").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            System.out.println("t1启动");
                for (int i=0; i<10; i++) {
                    t.add(new Object());
                    System.out.println("欢迎关注掌上编程公众号" + i);

                    if (t.size() == 5) {
                        //打开门闩 让t2得以进行
                        latch.countDown();
                    }
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
        },"t1").start();

    }

}

operation result

Guess you like

Origin www.cnblogs.com/mzdljgz/p/11641713.html