CountDownLatch/CyclicBarrier/Semahore/sychronize/locy区别

CountDownLatch:线程执行完毕之后唤醒主线程往下运行

CyclicBarrier:就像栅栏一样,等所有人迈过,又回到同一起跑线之后继续走自己的路

Semahore:信号量,控制资源占用

sychronize:同步控制关键字,容易发生死锁,在低竞争的时候性能比较好,用法简单

lock:可以配置超时时间,适用于高竞争环境,一定要注意释放锁

package test;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;

/**
 * Created by wzm on 2016/9/21.
 */
public class CyclicBarrierTest {

    public static void main(String[] args) {
        int n = 5;
        CyclicBarrier barrier = new CyclicBarrier(n);
        CountDownLatch latch = new CountDownLatch(n);
        Semaphore semaphore = new Semaphore(n);
        int workerNum = 10;
        /*for (int i=0; i<n; i++) {
            new Thread(new Worker(barrier, latch)).start();
        }*/
        for (int i=0; i<10; i++) {
            new Machine(semaphore, i).start();
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("主线程执行");
    }

    static class Worker implements Runnable {
        private CyclicBarrier barrier;
        private CountDownLatch latch;

        public Worker(CyclicBarrier barrier, CountDownLatch latch) {
            this.barrier = barrier;
            this.latch = latch;
        }

        public void run() {
            System.out.println(Thread.currentThread().getName() + "正在执行");
            try {
                barrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "执行完毕");
            latch.countDown();
        }
    }

    static class Machine extends Thread {
        Semaphore semaphore;
        int i;
        public Machine(Semaphore semaphore, int i) {
            this.semaphore = semaphore;
            this.i = i;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire();
                System.out.println("工人"+i+"占用到机器开始生产");
                Thread.sleep(100);
                semaphore.release();
                System.out.println("工人"+i+"生产完成,释放机器");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值