1. Read-Write Lock
1 // exclusive lock (write lock): You can only be a thread owns 2 // Shared lock (read lock): may be multiple threads simultaneously occupy 3 // operating results analysis: write lock guarantee atomicity operation, read lock does not guarantee atomic operations of 4 // Note: lock lock must be paired, or may cause a deadlock 5 // personal understanding: that is, modify the data write operation, it will change the original data, it is necessary to ensure that the write operation integrity, 6 // can not be interrupted in the middle, it can not be used simultaneously by multiple threads call 7 // read operation is the query data, the original data does not change, it can be called simultaneously by multiple threads 8 9 public class {ReadWriteLockDemo1 10 public static void main (String [] args) { . 11 myCacheLock myCacheLock = new new myCacheLock (); 12 is 13 is for (int i = 1; i <= 5; i++) { 14 int temp = i; 15 new Thread(() -> { 16 myCacheLock.write(temp, "_" + temp + "_"); 17 }).start(); 18 } 19 20 for (int i = 1; i <= 5; i++) { 21 int temp = i; 22 new Thread(() -> { 23 myCacheLock.read(temp); 24 }).start(); 25 } 26 } 27 } 28 29 class MyCacheLock { 30 Private volatile the Map <Integer, Object> = Map new new the HashMap <> (); 31 is // create a read-write lock 32 ReadWriteLock = Lock new new ReentrantReadWriteLock with (); 33 is 34 is // write 35 public void write (Integer Key, Object value) { 36 // write lock lock 37 [ lock.writeLock () lock ();. 38 is the try { 39 // service code 40 System.out.println(Thread.currentThread().getName() + "写入" + key); 41 map.put(key, value); 42 System.out.println(Thread.currentThread().getName() + "写入成功"); 43 } catch (Exception e) { 44 e.printStackTrace(); 45 } finally { 46 // 释放写锁 47 lock.writeLock().unlock(); 48 } 49 } 50 51 // 读 52 public void read(Integer key) { 53 // read lock lock 54 is lock.readLock () Lock ();. 55 the try { 56 is // service code 57 is System.out.println (. Thread.currentThread () getName () + "read" + Key); 58 Object value = as map.get (Key); 59 System.out.println (. Thread.currentThread () getName () + "read result" + value); 60 } the catch (Exception E) { 61 is e.printStackTrace ( ); 62 is } the finally { 63 is // release the read lock 64 lock.readLock () UNLOCK ().; 65 } 66 } 67 }
2. blocking queue
Blocking: when the queue is full, further kept inside, this time will block; when the queue is empty, but also to take out, at this time will be blocked.
Why do we use blocking queue?
In multithreading, communication between threads, we need to care about is the thread - wake up!
For example: In the message delivery process, before the message sender and receiver to resolve the blocking problem by asynchronous messaging middleware MQ.
. 1 // PUT (E E) has been waiting 2 // the offer (E E, Long timeout, TimeUnit Unit) time-out period, i.e. the queue is full or return to false . 3 // offter (E E) returns false, not reported abnormal 4 // add (E e) performing line reported abnormal a java.lang.IllegalStateException: queue Full . 5 public class BlockingDemo { . 6 public static void main (String [] args) throws InterruptedException { . 7 // parameters: initial capacity is set to the queue. 3 . 8 ArrayBlockingQueue with = Queue new new ArrayBlockingQueue with <> (. 3 ); . 9 10 // add an element 11 queue.put (. 1 ); 12 is // extracted twice 13 is System.out.println (queue.take ()); 14 System.out.println (queue.take ()); // perform this, waits 15 16 . 17 // PUT (E E) additive element 18 is / * queue.put (. 1); . 19 queue.put (2); 20 is queue.put (. 3); 21 is queue.put (. 4); // perform this , waits 22 is 23 is System.out.println (queue.poll ()); //. 1 24 System.out.println (queue.poll ()); // 2 25 System.out.println (queue.poll () ); 3 // 26 System.out.println (queue.poll ()); // null 27 * / 28 29 // --------------------------- -------------------------------- 30 // the offer (E E, Long timeout, TimeUnit Unit) additive element 31 / * System.out.println (Queue.offer (. 1, 3L, TimeUnit.SECONDS)); // to true 32 System.out.println (Queue.offer (2, 3L, TimeUnit.SECONDS)); // to true 33 is the System .out.println (Queue.offer (. 3, 3L, TimeUnit.SECONDS)); // to true 34 is System.out.println (Queue.offer (. 4, 3L, TimeUnit.SECONDS)); // wait 3 seconds, false (timeout wait, i.e. the queue is full or return to false) 35 * / 36 37 [ // ---------------------------------------------------------------- 38 // offter(E e)添加元素 39 /*System.out.println(queue.offer(1)); // true 40 System.out.println(queue.offer(2)); // true 41 System.out.println(queue.offer(3)); // true 42 System.out.println(queue.offer(4)); // 返回false,不报异常 43 44 System.out.println(queue.poll()); // 1 45 System.out.println(queue.poll()); // 2 46 System.out.println(queue.poll()); // 3 47 System.out.println(queue.poll()); // null 48 */ 49 50 // ------------------------------------------------ - 51 is // the Add (E E) additive element 52 is / * queue.add (. 1); 53 is queue.add (2); 54 is queue.add (. 3); 55 // add the fourth element 56 is queue.add ( 4); // this line reported abnormal perform a java.lang.IllegalStateException: Full Queue 57 is 58 System.out.println (queue.remove ()); 59 System.out.println (queue.remove ()); 60 the System. Out.println (queue.remove ()); 61 is System.out.println (queue.remove ()); 62 is * / 63 is } 64 }
Special blocking queue - Queue Synchronization
1 // synchronous queue 2 public class SynchronousQueueDemo { . 3 public static void main (String [] args) { . 4 // special queue capacity is fixed to the blocking 1 . 5 SynchronousQueue <Object> = Queue new new SynchronousQueue <> (); . 6 . 7 / / additive element . 8 new new the Thread (() -> { . 9 the try { 10 // delay to see the effect . 11 TimeUnit.SECONDS.sleep (. 3 ); 12 is queue.put (. 1 ); 13 is TimeUnit.SECONDS.sleep(3); 14 queue.put(2); 15 TimeUnit.SECONDS.sleep(3); 16 queue.put(3); 17 } catch (InterruptedException e) { 18 e.printStackTrace(); 19 } 20 },"A").start(); 21 22 // 取出元素 23 new Thread(() -> { 24 try { 25 TimeUnit.SECONDS.sleep(3); 26 System.out.println(queue.take()); 27 TimeUnit.SECONDS.sleep(3); 28 System.out.println(queue.take()); 29 TimeUnit.SECONDS.sleep(3); 30 System.out.println(queue.take()); 31 } catch (InterruptedException e) { 32 e.printStackTrace(); 33 } 34 },"B").start(); 35 } 36 }
3. Thread Pool
Pool technology: running consumes system resources, improve the utilization of the program, reduce our consumption of a performance
Thread pool, connection pool, memory pool object pool ......
Why use a thread pool? Thread multiplexing
Thread Pool:
Three methods:
1. Executors.newSingleThreadExecutor () single embodiment, only one thread
2. Executors.newFixedThreadPool (5) a fixed number of threads parameters: the number of threads
3. Executors.newCachedThreadPool () variable number of threads, scalable
Seven parameters:
1. int // number of core pool of threads corePoolSize
2. int maximumPoolSize // maximum number of threads
3. Long keepAliveTime // Timeout waiting time
4. TimeUnit Unit time unit parameter // keepAliveTime
5. The BlockingQueue <the Runnable> workQueue // blocking queue
6. ThreadFactory threadFactory // thread factory
7. RejectedExecutionHandler Handler // deny policy (see below)
Four kinds of denial strategy:
1. AbortPolicy () // Direct reported abnormal, discarding task
2. DiscardOldestPolicy () // before the thread pool is closed, try to get
3. DiscardPolicy () // return directly
4. CallerRunsPolicy () // where he comes back to where to go
. 1 public class ThreadPoolExecutorDemo1 { 2 public static void main (String [] args) { . 3 the ThreadPoolExecutor = Executor new new the ThreadPoolExecutor ( . 4 2, // the core thread pool number . 5 5 // maximum number of threads . 6 5L, // timeout for 7 TimeUnit.SECONDS, // keepAliveTime time unit parameter . 8 new new LinkedBlockingDeque with <> (. 3), // blocking queue 9 Executors.defaultThreadFactory(), // 线程工厂 10 new ThreadPoolExecutor.AbortPolicy() // 拒绝策略 11 ); 12 13 /* 14 * new ThreadPoolExecutor.CallerRunsPolicy() // 从哪来回哪去 15 * new ThreadPoolExecutor.DiscardOldestPolicy() // 线程池关闭之前,尝试去获取 16 * new ThreadPoolExecutor.DiscardPolicy() // 直接返回 17 * new ThreadPoolExecutor.AbortPolicy()// 直接报异常,丢弃任务 18 */ 19 20 try { 21 for (int i = 0; i < 15; i++) { 22 executor.execute(() -> { 23 System.out.println(Thread.currentThread().getName() + "__ok"); 24 }); 25 } 26 } catch (Exception e) { 27 e.printStackTrace(); 28 } finally { 29 // 关闭线程池 30 executor.shutdown(); 31 } 32 } 33 }
最大线程池 该如何设置?
CPU密集型: Runtime.getRuntime().availableProcessors() 获取当前CPU核数
IO密集型: 假设当前有50个线程都是进程经常操作大IO资源的,比较耗时! 我们则需要保证设置的线程池数量大于 50