JUC之lock

CountDownLatch
/**
 * @desc 倒计时
 *  5个人都走了,才关门?
 * @Author xw
 * @Date 2019/8/9
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(5);
        for(int i = 1; i <= 5; i++) { // 5个同学
            new Thread(() -> {
                try {
                    System.out.println(Thread.currentThread().getName() + "离开");
                    TimeUnit.SECONDS.sleep(1);
                    countDownLatch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, "同学[" + i + "]").start();
        }
        countDownLatch.await();
        System.out.println("班长关门");
    }
}
CyclicBarrierDemo
/**
 * @desc 计数器
 *  5个人都到齐了才出发
 * @Author xw
 * @Date 2019/8/9
 */
public class CyclicBarrierDemo {
    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
        for (int i = 1; i <= 5; i++) {
            new Thread(() -> {
                try {
                    System.out.println(Thread.currentThread().getName() + "同学到了");
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }, "T" + i).start();
        }
        while ((cyclicBarrier.getNumberWaiting()+1) != 5) {

        }
        System.out.println("人数到齐准备出发!");
    }
}
Semaphore
/**
 * @desc 信号量
 *  停车场(5个车位,20人抢)
 * @Author xw
 * @Date 2019/8/9
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(5); // 停车场只有5个车位
        for (int i = 1; i <= 20; i++) { // 20个人抢车位
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "》》》》抢到车位");
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "离开了=======");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            }, "同学" + i).start();
        }
    }
}
View Code
ReentrantReadWriteLock
/**
 * @desc 读写锁
 *  多个线程操作一个资源类,所以为了满足并发量,读取共享资源应该可以同时进行。
 *  写操作:原子 + 独占,整个过程必须是一个整体,中间不能被分解、打断
 *  小总结:
 *      读读共存
 *      读写互斥
 *      写写互斥
 * @Author xw
 * @Date 2019/8/20
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        for (int i = 1; i <= 5; i++) {
            final int tempInt = i;
            new Thread(() -> {
                myCache.put(tempInt + "", tempInt + "");
            }, String.valueOf(i)).start();
        }

        for (int i = 1; i <= 5; i++) {
            final int tempInt = i;
            new Thread(() -> {
                myCache.get(tempInt + "");
            }, String.valueOf(i)).start();
        }

    }
}

class MyCache {
    private volatile Map<String, Object> map = new HashMap<>();
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    //
    public void put(String key, Object value) {
        lock.writeLock().lock();
        System.out.println(Thread.currentThread().getName() + "\t 正在写入:" + key);
        try { TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); }
        map.put(key, value);
        System.out.println(Thread.currentThread().getName() + "\t 写入完成:" + key);
        lock.writeLock().unlock();
    }
    //
    public void get(String key) {
        lock.readLock().lock();
        System.out.println(Thread.currentThread().getName() + "\t 正在读取:" + key);
        try { TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); }
        Object value = map.get(key);
        System.out.println(Thread.currentThread().getName() + "\t 读取完成:" + value);
        lock.readLock().unlock();
    }
}
View Code

奇偶数

/**
 * @desc TODO
 * @Author xw
 * @Date 2019/8/9
 */
public class OddEventDemo {

    public static void main(String[] args) {
        
        //重入锁,ReentrantLock
        Lock lock = new ReentrantLock();
        OddEventNum oddEventNum = new OddEventNum();
        new Thread(() -> {
            while (oddEventNum.num < 100) {
                if (oddEventNum.flag) {
                    lock.lock();
                    System.out.println(" 奇数:" + oddEventNum.num);
                    oddEventNum.num++;
                    oddEventNum.flag = false; // 改变标识位
                    lock.unlock();
                }
                /*synchronized (oddEventNum) {
                    if (!oddEventNum.flag) { // 偶数
                        try {
                            oddEventNum.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        System.out.println(" 奇数:" + oddEventNum.num);
                        oddEventNum.num++;
                        oddEventNum.flag = false; // 改变标识位
                        oddEventNum.notify();
                    }
                }*/
            }
        }, "Odd").start();
        new Thread(() -> {
            while (oddEventNum.num <= 100) {
                if (!oddEventNum.flag) {
                    lock.lock();
                    System.out.println(" 偶数:" + oddEventNum.num);
                    oddEventNum.num++;
                    oddEventNum.flag = true; // 改变标识位
                    lock.unlock();
                }
                /*synchronized (oddEventNum) {
                    if (oddEventNum.flag) { // 奇数
                        try {
                            oddEventNum.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        System.out.println(" 偶数:" + oddEventNum.num);
                        oddEventNum.num++;
                        oddEventNum.flag = true; // 改变标识位
                        oddEventNum.notify();
                    }
                }*/
            }
        }, "Event").start();
    }
}

class OddEventNum {
    volatile int num = 1; // 从1开始
    boolean flag = true; // 奇数
}
View Code
CopyOnWriteArrayList
/**
 * @desc 锁demo
 *  多线程异常:java.util.ConcurrentModificationException
 *  (1) Vector
 *  (2) synchronizedList
 *  (3) CopyOnWriteArrayList
 * @Author xw
 * @Date 2019/8/8
 */
public class LockDemo {
    public static void main(String[] args) throws InterruptedException {
//        List<Integer> list = new ArrayList<>();
//        Vector<Integer> list = new Vector<>();
//        List<Integer> list = Collections.synchronizedList(new ArrayList<>());
        List<Integer> list = new CopyOnWriteArrayList();
        for (int i = 1; i <= 10000; i++) {
            new Thread(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                    list.add(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },"T" + i).start();
        }
        TimeUnit.SECONDS.sleep(2);
        System.out.println(list.size());
    }
}
View Code

 

转载于:https://www.cnblogs.com/ice-line/p/11385476.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值