关于高并发的几个基本锁的学习ReentrantLock,CountDownLatch ,CyclicBarrier,Semaphore,reentrantReadWriteLock

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/*
 * 学习常用的几个锁的类
 * 1.ReentrantLock  可重用锁
 *
 * 2.CountDownLatch  场景:任务需要在几个线程后才能执行,类似于一个计数器
 *
 * 3.CyclicBarrier  循环屏障   任务会在几个线程都到达时,才会一起执行,还有一个高级构造方法actionBarrier来进行优先处理
 *
 * 4.Semaphore  信号量     用于限制并发线程的数量
 *
 * 5.reentrantReadWriteLock  实现一个缓存器
 * */
public class LockStudy {
    @Test
    public void ReentrantLockTest() {
        final ReentrantLock rl = new ReentrantLock();
        new Thread(new Runnable() {
            public void run() {
                try {
                    rl.lock();
                    Thread.sleep(3000);
                    System.out.println("子线程" + rl.getHoldCount());
                } catch (Exception e) {
                    System.out.println("线程上锁异常");
                } finally {
                    rl.unlock();
                }

            }
        }).start();

        try {
            Thread.sleep(1000);
            rl.lock();
            System.out.println("主线程的阻塞长度" + rl.getQueueLength());
        } catch (Exception e) {
            System.out.println("主线程上锁失败");
        } finally {
            rl.unlock();
        }
    }

    @Test
    public void CountDownLatch() {
        final CountDownLatch cdl = new CountDownLatch(4);

        //3个线程后,才会执行下面的业务
        for (int i = 0; i < 3; i++) {
            new Thread(new Runnable() {
                public void run() {
                    System.out.println("子线程");
                    cdl.countDown();
                }
            }).start();
        }
        try {
            cdl.await(3, TimeUnit.SECONDS);
        } catch (Exception e) {
            System.out.println("超时自动中断");
        } finally {
            System.out.println("执行业务代码");
        }

    }

    public volatile int i = 0;

    @Test
    public void CyclicBarrierTest() {
        final CyclicBarrier cyclicBarrier = new CyclicBarrier(3);

        new Thread(new Runnable() {
            public void run() {
                try {
                    System.out.println("第一个子线程准备好了");
                    cyclicBarrier.await();
                } catch (Exception e) {
                    System.out.println("第一个++++子线程+++阻塞失败");
                } finally {
                    System.out.println("子线程执行了");
                    i++;
                    System.out.println("子线程的运行结果" + i);
                }

            }
        }).start();
        new Thread(new Runnable() {
            public void run() {
                try {
                    System.out.println("第二个子线程准备好了");

                    cyclicBarrier.await();
                } catch (Exception e) {
                    System.out.println("子线程的子线程++++阻塞失败");
                } finally {
                    System.out.println("第二个子线程执行了");
                    i++;
                    System.out.println("子线程的运行结果" + i);
                }
            }
        }).start();
        try {
            try {
                System.out.println("主线程线程准备好了");
                Thread.sleep(3000);


            } catch (Exception e) {
                System.out.println("线程睡眠失败");
            }
            cyclicBarrier.await();
        } catch (Exception e) {
            System.out.println("第二个+++主线程++++阻塞失败");
        } finally {
            System.out.println("主线程执行了");
            i++;
            System.out.println("主线程结果" + i);
        }


    }

    @Test
    public void resTest() {
        try {
            CyclicBarrierTest();
            Thread.sleep(3000);
        } catch (Exception e) {

        } finally {
            System.out.println("最终结果" + i);
        }


    }

    @Test
    public void semaphoreTest() {
        final Semaphore semaphore = new Semaphore(2);

        for (int i = 0; i < 8; i++) {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        System.out.println("获取资源");
                        semaphore.acquire();

                        Thread.sleep(2000);
                        System.out.println("使用资源");
                        //semaphore.release();

                        System.out.println("释放资源");
                    } catch (Exception e) {
                        System.out.println("异常");
                    }

                }
            }).start();
        }
    }

    @Test
    public void driverCarTest() {
        for (int i = 0; i < 3; i++) {
            Driver driver = new Driver();
            new car(driver).start();
        }
    }

    @Test
    public void ReentrantReadWriteLockTest() {
        for (int i=0;i<6;i++){
            new Thread(new Runnable() {
                public void run() {
                    ReentrantReadWriteLockDome demo=new ReentrantReadWriteLockDome();
                    demo.get("1");
                    System.out.println(demo.get("1")+"读数据");
                }
            }).start();

        }
        for (int i=0;i<4;i++){
            new Thread(new Runnable() {
                public void run() {
                    ReentrantReadWriteLockDome demo=new ReentrantReadWriteLockDome();
                    demo.put("1","hehe");
                }
            }).start();
        }
    }

    //实例使用semaphore
    class Driver {
        final Semaphore semaphore = new Semaphore(1);

        public void driverCar() {
            try {
                semaphore.acquire();
                System.out.println("司机开始开车" + Thread.currentThread().getName() + "时间" + System.currentTimeMillis());

                semaphore.release();
                System.out.println("司机下车" + Thread.currentThread().getName() + "时间" + System.currentTimeMillis());

            } catch (Exception e) {
                System.out.println("线程异常");
            }
        }
    }

    class car extends Thread {
        private Driver driver;

        car(Driver driver) {
            super();
            this.driver = driver;
        }

        @Override
        public void run() {
            driver.driverCar();
        }
    }

    //读写锁的使用
    class ReentrantReadWriteLockDome{

        private Map map = new HashMap();
        private final ReentrantReadWriteLock rrwl = new ReentrantReadWriteLock();
        public Object get(String id) {
            Object data=map.get(id);
            try {
                rrwl.readLock().lock();
                if (map.get(id) != null) {
                    System.out.println("map有数据" + Thread.currentThread().getName() + "数据:" + data);

                } else {
                    System.out.println("没有数据"+Thread.currentThread().getName());
                    data=null;
                }
            } catch (Exception e){
                System.out.println("中断异常");
            }finally {
                rrwl.readLock().unlock();
            }
            return data;
        }

        public void put(String id,String data){
            rrwl.writeLock().lock();
            map.put(id,data);
            System.out.println(Thread.currentThread().getName()+"写数据"+data);
            rrwl.writeLock().unlock();
        }
    }
}

你可能感兴趣的:(java高并发基础,java)