JUC并发工具类

CountDownLatch

倒计时,做减法计算,count=0,唤醒阻塞线程。

public class App {

    public static void main(String[] args) throws InterruptedException {
        new App().test();
    }

    public void test() throws InterruptedException {
        long start = System.currentTimeMillis();
        doTask();
        long end = System.currentTimeMillis();
        System.out.println("耗时(s):" + (end - start) / 1000);
    }

    private void doTask() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(10);
	// 控制主线程最后执行
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(()->{
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName());
                countDownLatch.countDown();
            });
            thread.start();
        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName() + " finish");
    }

}
Thread-1
Thread-4
Thread-8
Thread-3
Thread-5
Thread-6
Thread-2
Thread-0
Thread-9
Thread-7
main finish
耗时(s)2

CyclicBarrier

可循环利用的屏障,做加法计算,count=屏障值(parties),唤醒阻塞线程。

相比CountDownLatch的一次性,CyclicBarrier是可循环利用的。

public class App {

    public static void main(String[] args) throws InterruptedException {
        new App().test();
    }

    public void test() {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5, ()->{
            System.out.println(Thread.currentThread().getName() + " 等待完成后,优先执行该Runnable");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + " 出发!");
        });
        // 可循环的栅栏,需要等待同伴(parties个)到齐。
        for (int i = 0; i < 4; i++) {
            Thread thread = new Thread(()->{
                try {
                    System.out.println(Thread.currentThread().getName());
                    cyclicBarrier.await();
                    System.out.println(Thread.currentThread().getName() + " finished");
                } catch (InterruptedException | BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            });
            thread.start();
        }

        try {
            Thread.sleep(5000);
            cyclicBarrier.await();
            System.out.println(Thread.currentThread().getName());
        } catch (InterruptedException | BrokenBarrierException e) {
            throw new RuntimeException(e);
        }
    }
}
Thread-0
Thread-3
Thread-2
Thread-1
main 等待完成后,优先执行该Runnable
main 出发!
main
Thread-0 finished
Thread-1 finished
Thread-3 finished
Thread-2 finished

Semaphore

控制最大的线程并发数,用来做流量控制。

好比疫情下,超市最大只允许n人购物,其他人只能在外等待里面的人出来。

public class App {

    public static void main(String[] args) throws InterruptedException {
        new App().test();
    }

    public void test() {
        Semaphore semaphore = new Semaphore(1);
        // 控制执行线程数量
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName());
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    semaphore.release();
                }
            });
            thread.start();
        }

        System.out.println(Thread.currentThread().getName());
    }
}

Thread-0
main
Thread-1
Thread-2
Thread-3
Thread-4
Thread-5
Thread-6
Thread-7
Thread-8
Thread-9

Exchanger

两个线程之间的数据交换,Exchange是 阻塞形式的,两个线程要都到达执行Exchange函数才会交换。

public class App {

    public static void main(String[] args) throws InterruptedException {
        new App().test();
    }

    public void test() {
        Exchanger<String> exchanger = new Exchanger<>();
        // 线程之间的数据交换
        for (int i = 0; i < 4; i++) {
            int finalI = i;
            Thread thread = new Thread(() -> {
                try {
                    String exchange = exchanger.exchange("我是线程" + finalI);
                    System.out.println(Thread.currentThread().getName() + " exchange: " + exchange);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            thread.start();
        }

    }
}

Thread-3 exchange: 我是线程2
Thread-2 exchange: 我是线程3
Thread-0 exchange: 我是线程1
Thread-1 exchange: 我是线程0

附录-简单实现

利用wait和notify也可以自己简单实现上述四个类功能

/**
 * MyCountDownLatch
 * @author admin
 */
public class App {

    public static void main(String[] args) {
        MyCountDownLatch countDownLatch = new MyCountDownLatch(2);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(1);
                countDownLatch.countDown();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println(2);
                countDownLatch.countDown();
            }
        }).start();

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(3);
    }

    static class MyCountDownLatch {

        int count = 0;

        public MyCountDownLatch(int count) {
            this.count = count;
        }

        public void await() throws InterruptedException {
            synchronized (this) {
                if (count > 0) {
                    wait();
                }
            }
        }

        public void countDown() {
            synchronized (this) {
                if (--count == 0) {
                    notifyAll();
                }
            }
        }
    }
}

/**
 * MyCyclicBarrier
 * @author admin
 */
public class App2 {

    public static void main(String[] args) {
        MyCyclicBarrier cyclicBarrier = new MyCyclicBarrier(3);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("1---1");
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("1---2");
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("2---1");
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("2---2");
            }
        }).start();

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("3---1");
        try {
            cyclicBarrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("3---2");
    }

    static class MyCyclicBarrier {

        int count = 0;

        int threadWaitNum;

        public MyCyclicBarrier(int threadWaitNum) {
            this.threadWaitNum = threadWaitNum;
        }

        public void await() throws InterruptedException {
            synchronized (this) {
                count++;
                if (count == threadWaitNum) {
                    notifyAll();
                } else {
                    wait();
                }
            }
        }
    }
}

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * MySemaphore
 * @author admin
 */
public class App3 {

    public static void main(String[] args) {
        MySemaphore semaphore = new MySemaphore(2);

        for (int i = 0; i < 6; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName() + " " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                        Thread.sleep(1000);
                        semaphore.release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "线程-" + i);
            thread.start();
        }
    }

    static class MySemaphore {

        int count = 0;

        int permits;

        public MySemaphore(int permits) {
            this.permits = permits;
        }

        public void acquire() throws InterruptedException {
            synchronized (this) {
                if (count < permits) {
                    count++;
                } else {
                    wait();
                    acquire();
                }
            }
        }
        public void release() throws InterruptedException {
            synchronized (this) {
                count--;
                notify();
            }
        }
    }
}

/**
 * MyExchanger
 *
 * @author admin
 */
public class App4 {

    public static void main(String[] args) {
        MyExchanger<String> exchanger = new MyExchanger();

        Thread thread = new Thread(() -> {
            try {
                String a = "AAAAA";
                String b = exchanger.exchange(a);
                System.out.println(Thread.currentThread().getName() + " " + a + ", 交换后:" + b);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "线程-A");
        thread.start();

        Thread thread2 = new Thread(() -> {
            try {
                String b = "BBBBB";
                String a = exchanger.exchange(b);
                System.out.println(Thread.currentThread().getName() + " " + b + ", 交换后:" + a);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "线程-B");
        thread2.start();
    }

    static class MyExchanger<T> {

        T value;

        public T exchange(T exchangeValue) throws InterruptedException {
            synchronized (this) {
                if (value != null) {
                    T v = value;
                    value = exchangeValue;
                    notify();
                    return v;
                } else {
                    value = exchangeValue;
                    wait();
                    return exchange(null);
                }
            }
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值