闭锁CountDownLatch

package concurrent._ReentrantLock;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//一个关于Lock的最基本操作,lock.lock()与lock.unlock()
public class MyReentrantLock {

    private static Lock lock = new ReentrantLock();
    private static int count = 0;
    private static CountDownLatch countDownLatch = new CountDownLatch(3);
    public static void main(String[] args) throws InterruptedException {
        MyReentrantLock mylock = new MyReentrantLock();

        Thread a = new Thread("A"){
            @Override
            public void run() {
                mylock.lockinsert(Thread.currentThread());
            }
        };
        a.start();
        Thread b = new Thread("B"){
            @Override
            public void run() {
                mylock.lockinsert(Thread.currentThread());
            }
        };
        b.start();
        Thread c = new Thread("C"){
            @Override
            public void run() {
                mylock.lockinsert(Thread.currentThread());
            }
        };
        c.start();

        //等待三个线程结束后输出count的值,可以使用一个闭锁
        //Thread.sleep(1000);
        System.out.println("等待三个线程结束");
        countDownLatch.await();
        System.out.println(count);
        



    }

    public void lockinsert(Thread thread){
        lock.lock();
        //线程如果没有获得锁,就会阻塞在此处,获得锁之后才能后续操作

        try{
            System.out.println("线程" + thread.currentThread().getName() + "获得了锁");

            for(int i = 0 ; i < 1000 ; i ++){
                count++;
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("线程" + thread.currentThread().getName() + "释放了锁");

            lock.unlock();
            countDownLatch.countDown();
        }
    }



}

结果显示;

线程A获得了锁
线程A释放了锁
等待三个线程结束
线程C获得了锁
线程C释放了锁
线程B获得了锁
线程B释放了锁
3000

闭锁只能用一次

posted @ 2018-11-26 21:20  式微胡不归  阅读(144)  评论(0编辑  收藏  举报