package com.thread; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class Test1 { private static int value = 0; static Lock lock = new ReentrantLock(); private static ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private static Lock readLock = readWriteLock.readLock(); private static Lock writeLock = readWriteLock.writeLock(); private static void read(Lock lock) { lock.lock(); try { Thread.sleep(1000); System.out.println("read over" + value); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } private static void write(Lock lock, int v) { lock.lock(); try { Thread.sleep(1000); value = v; System.out.println("write over" + value); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public static void main(String[] args) { ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 20, 5000, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(5)); Runnable runnable1 = new Runnable() { @Override public void run() { read(readLock); } }; Runnable runnable2 = new Runnable() { @Override public void run() { write(writeLock, 2); } }; for (int i = 0; i < 18; i++) { threadPoolExecutor.execute(runnable1); } for (int i = 0; i < 2; i++) { threadPoolExecutor.execute(runnable2); } } }