PS:整理自极客时间《Java并发编程》编程
1. 概述数组
2. Java内存模型缓存
3. 互斥锁sychronized安全
class Allocator { private List<Object> als; // 一次性申请全部资源 synchronized void apply( Object from, Object to){ // 经典写法 while(als.contains(from) || als.contains(to)){ try{ wait(); }catch(Exception e){ } } als.add(from); als.add(to); } // 归还资源 synchronized void free( Object from, Object to){ als.remove(from); als.remove(to); notifyAll(); } }
4. 线程的生命周期多线程
6. 线程的性能指标并发
7. JDK并发包app
8. 线程池异步
1 // 简化的线程池,仅用来讲明工做原理 2 class MyThreadPool{ 3 // 利用阻塞队列实现生产者 - 消费者模式 4 BlockingQueue<Runnable> workQueue; 5 // 保存内部工做线程 6 List<WorkerThread> threads 7 = new ArrayList<>(); 8 // 构造方法 9 MyThreadPool(int poolSize, 10 BlockingQueue<Runnable> workQueue){ 11 this.workQueue = workQueue; 12 // 建立工做线程 13 for(int idx=0; idx<poolSize; idx++){ 14 WorkerThread work = new WorkerThread(); 15 work.start(); 16 threads.add(work); 17 } 18 } 19 // 提交任务 20 void execute(Runnable command){ 21 workQueue.put(command); 22 } 23 // 工做线程负责消费任务,并执行任务 24 class WorkerThread extends Thread{ 25 public void run() { 26 // 循环取任务并执行 27 while(true){ ① 28 Runnable task = workQueue.take(); 29 task.run(); 30 } 31 } 32 } 33 } 34 35 /** 下面是使用示例 **/ 36 // 建立有界阻塞队列 37 BlockingQueue<Runnable> workQueue = 38 new LinkedBlockingQueue<>(2); 39 // 建立线程池 40 MyThreadPool pool = new MyThreadPool( 41 10, workQueue); 42 // 提交任务 43 pool.execute(()->{ 44 System.out.println("hello"); 45 });
9. 鸟瞰并行任务分类异步编程