CopyOnWriteArrayList
set
Callable
常用的辅助类:必会
CountDownLatch :减法计数器
CyclicBarrier: 加法计数器
Semaphore 信号量
读写锁
import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * @author : lijie * @Description: 独占锁(写锁):一次只能被一个线程锁拥有 共享锁(读锁):多个线程可以同时拥有 读--读 可以共存 读--写 不可以共存 写--写 不可以共存 * @date Date : 2021年08月22日 20:43 */ public class ReadWriteLockDemo { public static void main(String[] args) { final MyCache cache = new MyCache(); // 写入 for (int i = 1; i <= 5; i++) { int tmp = i; new Thread(() -> cache.put(tmp + "", tmp + ""), String.valueOf(i)).start(); } // 读取 for (int i = 1; i <= 5; i++) { int tmp = i; new Thread(() -> cache.get(tmp + ""), String.valueOf(i)).start(); } } } class MyCache { private volatile Map<String, String> map = new HashMap<>(); // 读写锁,更加细粒度的控制 private ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); public void put(String key, String val) { readWriteLock.writeLock().lock(); try { System.out.println(Thread.currentThread().getName() + "写入" + key); map.put(key, val); System.out.println(Thread.currentThread().getName() + "写入结束"); } catch (Exception e) { e.printStackTrace(); } finally { readWriteLock.writeLock().unlock(); } } // 读取,所有人都可以读 public void get(String key) { readWriteLock.readLock().lock(); try { System.out.println(Thread.currentThread().getName() + "读取" + key); final String s = map.get(key); System.out.println(Thread.currentThread().getName() + "读取结束"); } catch (Exception e) { e.printStackTrace(); } finally { readWriteLock.readLock().unlock(); } } }
获取IO的常用大型任务的个数,然后乘以2即可