package com.stock.test.base.thread; import org.junit.Test; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class LockTest { private Lock lock = new ReentrantLock(); @Test public void testReentrantLock() throws InterruptedException { new Thread(new Runnable() { @Override public void run() { try { System.out.println(Thread.currentThread().getName()+"--->进入"); lock.lock(); Thread.sleep(2000); System.out.println(Thread.currentThread().getName()+"--->退出"); }catch (Exception e){ e.printStackTrace(); }finally { lock.unlock(); } } },"Thread--1").start(); new Thread(new Runnable() { @Override public void run() { try { System.out.println(Thread.currentThread().getName()+"--->进入"); lock.lock(); System.out.println(Thread.currentThread().getName()+"--->退出"); }catch (Exception e){ e.printStackTrace(); }finally { lock.unlock(); } } },"Thread--2").start(); synchronized (this){ this.wait(10000); } } @Test public void testCondition() throws InterruptedException { Lock lock = new ReentrantLock(); Condition condition = lock.newCondition(); new Thread(new Runnable() { @Override public void run() { try { System.out.println(Thread.currentThread().getName()+"--->进入"); lock.lock(); Thread.sleep(2000); condition.await(); System.out.println(Thread.currentThread().getName()+"--->退出"); }catch (Exception e){ e.printStackTrace(); }finally { lock.unlock(); } } },"Thread--1").start(); new Thread(new Runnable() { @Override public void run() { try { System.out.println(Thread.currentThread().getName()+"--->进入"); lock.lock(); condition.signal(); System.out.println(Thread.currentThread().getName()+"--->退出"); }catch (Exception e){ e.printStackTrace(); }finally { lock.unlock(); } } },"Thread--2").start(); synchronized (this){ this.wait(10000); } } @Test public void testSemaphore() throws InterruptedException { // 表示最多同时允许5个线程进入 Semaphore semaphore = new Semaphore(5); semaphore.acquire(); // 获取 semaphore.release(); // 释放 } @Test public void testWritOrReadLock(){ ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); ReentrantReadWriteLock.ReadLock readLock = lock.readLock(); ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock(); CyclicBarrier cyclicBarrier = new CyclicBarrier(3); new Thread(new Runnable() { @Override public void run() { } },"线程1").start(); } }
5、线程锁
最新推荐文章于 2024-09-12 23:58:52 发布