關於高併發的幾個基本鎖的學習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<String, Object> map = new HashMap<String, Object>();
        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();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章