Part of the thread pool basic knowledge of Java

  1, the basic concept

  1, shared resources

  Multiple threads to access (read or write) a copy of the same resource, the resource is known as a shared resource. How to ensure that multiple threads access to the data is the same, is called data synchronization or resource synchronization.

  2, thread communication

  Inter-thread communication, also known as internal process communication, and network communication process different communication; multiple threads to achieve mutually exclusive access to resources of time, it sends a signal to each other.

  2, synchronous, asynchronous, blocking, non-blocking

  Synchronous and asynchronous way is to get the result, blocking and non-blocking is whether to wait for the results to complete other things.

  Synchronous blocking (BIO), to wait for the client's data has been read, also need blocking client determines whether there is data.

  Synchronous non-blocking (NIO), you need to wait for the client's data has been read, but by way of polling data to determine whether the client can do other things.

  Asynchronous blocks, waiting for the results of a callback notification, cpu's in a dormant waiting.

  Asynchronous non-blocking (AIO), the operating system to complete the read operation, the read completion notification callback, use the thread pool way to poll the client data, you can do other things.

  Concurrent, single cpu can handle multiple tasks, but only one task at the same time run.

  Parallel multiple tasks to run on multiple cpu, the same real time operation.

  2, the life cycle

  3, daemon thread

  General use new Thread created thread are non-daemon thread, also known as user threads. To guard the way is that, before the run, call setDaemon (true). Daemon thread, just to serve user threads, so once all the user threads have finished running, the guardian would be the end. On the contrary, as long as there exists a non-daemon thread, then the guard would not terminate the thread.

  Daemon threads scenarios: garbage collection, heartbeat detection, spelling check thread

  com.vim package;

  import java.util.concurrent.TimeUnit;

  public class App {

  public static void main( String[] args ) throws Exception{

  Thread t = new Thread(()->{

  while (true){

  try {

  TimeUnit.SECONDS.sleep(1);

  System.out.println("......");

  }catch (Exception e){

  e.printStackTrace ();

  }

  }

  });

  // t only set up here, with the exit of the parent process will exit

  t.setDaemon(true);

  t.start();

  TimeUnit.SECONDS.sleep(5);

  System.out.println("main is over!");

  }

  }

  4, a thread yield, sleep

  After the yield, called threads concessions into RUNNABLE state from RUNNING state, it is possible to switch again to grab executive power, into the RUNNING state.

  sleep, can block the thread entered the BLOCKED state, and this was suspended, so that the cpu; only the blocking time is up, will enter RUNNABLE state, not necessarily immediately acquire the right to perform the cpu.

  The role of sleep (0) is triggered once the operating system immediately re-CPU competition, perhaps the result of competition still get current thread CPU control, may be replaced by another thread gets control of the CPU.

  com.vim package;

  public class App {

  public static void main( String[] args ) throws Exception {

  new Thread(()->{

  try {

  while (true){

  Thread.sleep(0);

  }

  }catch (Exception e){

  e.printStackTrace ();

  }

  }).start();

  }

  }

  5, thread interrupt

  wait, sleep, join the current thread into the blocked state, and interrupt can be interrupted blocked, but is merely intended to present traffic congestion state. InterruptException current thread will throw an exception as a signal notification. This notification will interrupt flag is set to true, but interrupted for a blocking state of the status bit is reset to false. Judged by thread.isInterrupted (), of course, in the blocking state, it will be removed, thus affecting the results of the method.

  package com.sample.modules.test;

  import java.util.concurrent.TimeUnit;

  public class Test {

  // interrupt a thread, interrupt bit true

  public static void test1() throws Exception{

  Thread t = new Thread(()->{

  // 2. Get the current state of the interrupt flag is true

  System.out.println(Thread.currentThread().isInterrupted());

  });

  t.start();

  // 1. Interrupt thread

  t.interrupt();

  TimeUnit.MINUTES.sleep(4);

  }

  // interrupt a thread, interrupt bit false

  public static void test2() throws Exception{

  Thread t = new Thread(()->{

  2 // Clear interrupt bit

  Thread.interrupted();

  3 // Get the current interrupt flag is false

  System.out.println(Thread.currentThread().isInterrupted());

  });

  t.start();

  // 1. Interrupt thread

  t.interrupt();

  TimeUnit.MINUTES.sleep(4);

  }

  // interrupt a thread, interrupt bit false

  public static void test3() throws Exception{

  Thread t = new Thread(()->{

  // 2 blocked interrupt wait, sleep, join the cause

  try {

  TimeUnit.SECONDS.sleep(5);

  }catch (InterruptedException e){

  System.out.println("i am interrupted");

  }

  3 // Get the current interrupt flag is false

  System.out.println(Thread.currentThread().isInterrupted());

  });

  t.start();

  // 1. Interrupt thread

  t.interrupt();

  TimeUnit.MINUTES.sleep(4);

  }

  // interrupt results before blocking: false, true, i am interrupted, false

  public static void test4(){

  Thread.interrupted();

  System.out.println("interrupt flag: "+Thread.currentThread().isInterrupted());

  Thread.currentThread().interrupt();

  System.out.println("interrupt flag: "+Thread.currentThread().isInterrupted());

  try {

  TimeUnit.SECONDS.sleep(1);

  }catch (InterruptedException e){

  System.out.println("i am interrupted");

  }

  System.out.println("interrupt flag: "+Thread.currentThread().isInterrupted());

  }

  public static void main(String[] args) throws Exception{

  test3 ();

  }

  }

  6, the thread join

  parent thread calls child thread join method, actually calls join (0), which added a lock, the thread loop to determine child survival status, of course, each call to wait (0) method cycle, so you can make other threads can also enter join (0) method.

  // current method is not locked

  public final void join() throws InterruptedException {

  join(0);

  }  Wuxi see male hospital Which https://yyk.familydoctor.com.cn/20612/

  // This method is locked, then other threads can enter the join (), but not into the join (0)

  // constantly check whether the thread alive, call wait (0), thus releasing the lock, other threads can enter join (0), that is, you can have multiple threads waiting for a thread is finished

  // Once the thread is not alive, then it will return to the join () method, the calling thread can continue execution

  public final synchronized void join(long millis){

  if (millis == 0) {

  while (isAlive()) {

  wait(0);

  }

  }

  }

  7, thread notifies notify, wait

  These two methods, derived from the Object class, with the use of both. wait method belongs to object methods, you must obtain before calling monitor lock of the object, after the call, it will release the monitor lock of the object to enter the object associated waitset and wait for other threads using notify wake.

  A typical production and consumption scenarios:

  Producers in the production of goods, the warehouse (Isochronous Resource) were locked, if the current warehouse is not full, then add products to use notifyAll notify the consumer; if the current warehouse is full, use the wait release the lock, enter waitset blocked notifyAll wait for notification.

  Consumers, consumption came to the warehouse, the warehouse (synchronous resources) to lock if the current warehouse products, then take the product, use notifyAll notify the producer; if the current warehouse is empty, use the wait release the lock, enter waitset blocking wait notifyAll notice.

  When notifyAll comes, for all producers and consumers, the opportunity to have a key to get the warehouse, the competition will go into more decision logic again.

  8 difference, wait and sleep in

  In common:

  The thread into the blocked state; interrupt can be interrupted;

  the difference:

  There is a wait Object, sleep is a unique Thread.

  wait process must run in synchronization, sleep required.

  wait will release the lock, if sleep on the synchronization method, and will not release the lock.

  9, exception handling thread

  package com.sample.modules.test;

  public class Test {

  public static void main(String[] args) throws Exception{

  Thread t = new Thread(()->{

  int i = 1/0;

  });

  t.setUncaughtExceptionHandler((thread, e)->{

  System.out.println("exception...");

  });

  t.start();

  }

  }

  10, computer memory model and the Java Memory Model

  Principle retrospective: cpu in the instruction execution time, data from the main memory (RAM), since both the speed and the like are not serious, occurred between the cache buffer; generally divided into L1, L2, L3 cache per CPU core comprising set of L1, L2 and L3 cache shared.

  Cache coherency problem: when a plurality of processors of a computing task referring to the same main memory area, each cpu variables removed from the main memory, into the local cache, then calculated, written into the cache, then the cache flushed to main memory.

  I read the main memory into the cache

  I ++ to be

  The write-back cache results

  Refresh the cache back to main memory.

  Cache coherency protocol: cpu operation data in the cache, if a shared variable is found, then at the time of writing, it will signal the other of the variable cpu cache line is invalidated, performing other cpu when the variable read, you need to go to the main memory read.

  Compared computer memory model, Java memory model: thread == CPU, working memory == CPU cache, main memory == main memory.

  12, the three major characteristics of concurrent programming

  Atomicity, multiple operation, either all be executed or all not be executed.

  Visibility, a thread of shared variables, has been modified, then other threads can see the value immediately after the modification.

  Orderliness, the program code during execution of the order.

  13, synchronized keyword

  synchronized keyword provides a mechanism to lock, to ensure mutually exclusive access to shared variables, namely the same time, only one thread synchronized access to resources.

  Terms of memory, monitor enter and monitor exit two JVM command to ensure that any thread must get data from main memory before the monitor enter, after the monitor exit, you must refresh the updated value to the main memory. Both JVM command, strict compliance happends-before principle, there must exist before a monitor enter instruction that is a monitor exit command.

  The keyword for exclusive access to a synchronized resource, very effective, but the other did not get to monitor the thread, in the end how long blocking, unblocking can not advance, these are unknown. To this end, java provides other solutions to explicitly lock for us. As ReentrantLock.

  14、AQS

  Exclusive

  #Obtain

  1, try to acquire resources successfully return immediately; if it fails, create an exclusive node, using the CAS added to the end of the queue to enter the spin state

  2, if the first node is a head node, again trying to obtain resources, success is set to head node; otherwise suspended, waiting to be awakened predecessor node

  # For the interrupts

  1, common acquisition, the interrupt occurs, the interrupt bit clears, and access to resources is successful, trigger an interrupt

  2, can get interrupted in the event of the interruption after, also clears the interrupt bit, but direct throw an exception interrupted

  #freed

  1, synchronized release status

  2, get the next node of the current node, wake

  Sharing mode

  #Obtain

  1, the synchronization acquisition state, if the return value is> = 0, then the sync state (state) has a residual acquiring a lock successfully returned directly

  2, the failure to add a node to the shared type Node tail of the queue, then the node enters the spin state

  3, the precursors for the first node if the node again determines whether the synchronization state (state) has a residual

  4, if it is, then the current node may perform, while the current node is set to the head node and all successor nodes awaken

  Difference between the two

  1, an exclusive lock is a synchronization status, i.e., only one thread at a time successfully obtained synchronization state; shared lock synchronization state> 1, the value is determined by the upper layer synchronization components

  2, an exclusive lock queue after completion of the release operation of the head node in its immediate successor node; shared lock queue head node release all the subsequent node run is completed

  Case 3, a plurality of shared lock will appear threads (i.e., queue node synchronization) while synchronization is successfully acquired state

  15, reentrant lock ReentrantLock

  #Obtain

  1, if you currently have a lock, and the owner is the current thread, increase the re-entry again

  2, if the lock is currently no direct attempt to acquire the lock mode will determine whether there is a fair waiting threads, direct attempts to monopolize resources under non-equity modes

  16, counter CountDownLatch

  1, using a shared mode, the setting state of a fixed number of initialization

  2, await method calls sync interrupt acquireShared method, rewriting tryAcquireShared acquisition mode, when the state reaches zero, it represents the resources available

  3, countDown method, the sync releaseShared method invocation, the state continues to be a Save

  17, read-write lock ReentrantReadWriteLock

  Write lock

  #Obtain

  1, currently in lock-free state, acquires a write lock in exclusive mode

  2, if you set writerShouldBlock, direct return false

  1, currently in a locked state

  2, there are read locks, direct return false

  3, write lock, if the current thread, the re-entry, false otherwise

  Read lock

  1, if there are write locks and write locks are not the current thread returns -1

  2, if there is no write lock, try to get a read lock, if you set readerShouldBlock, re-enter judgment

Guess you like

Origin www.cnblogs.com/djw12333/p/11206025.html