1. What is a thread

  • Single-core CPU = a workshop: execute a process at a time, if execute multiple programs, will switch back and forth in multiple processes, execute to the process will switch back and forth between multiple threads.

  • Multi-core CPU = one factory: multiple processes can be executed at a time;

  • Process: A workshop for a process (a running program); Process is a heavyweight resource. The system allocates memory and CPU resources, starts and stops slowly, and memory is independent of each other

  • Thread: a worker in a workshop is a thread;

  • Multithreading: a process containing more than one thread; Multiple threads can share the memory space of a process;

1.1. What is multithreading?
  • Multithreading is when the CPU switches to a process, it switches back and forth between multiple threads, and each thread is allocated a certain amount of CPU time. Threads are the unit of CPU allocation time
1.2. Parallelism and concurrency
  • Parallel: Multiple cpus execute multiple threads simultaneously
  • Concurrency: one CPU executes multiple threads at the same time, and the CPU switches back and forth between threads so that they can all execute (not at the same time)
1.3. Synchronous and asynchronous
  • Synchronization: Multiple instructions are executed sequentially. One instruction blocks the current thread while executing, and the others must be executed after that instruction completes.
  • Asynchrony: Multiple threads point to their own commands at the same time, and one thread notifies the other when it has finished executing it

2. Multi-threaded application scenarios

  • Large enterprise applications are characterized by high concurrency, because they will have a large number of users, such as Taobao, JINGdong, Douyin, etc. If the server is single-threaded, all users must queue for execution, and each user must be assigned a separate thread for each request to complete a separate task without affecting each other. Stand-alone applications (e.g., large games) need to perform a large number of tasks: graphics rendering, motion control, network communication, etc. Multiple threads are required to perform the above tasks simultaneously.

3. Methods for starting threads

3.1. Inheriting Thread
public class MyThread extends Thread{ @Override public void run() { for (int i = 0; i <100 ; I++) {system.out.println ("hello "+ thread.currentthread ().getname ()); } } public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.start(); / / a thread cannot call two above the start method of IllegalThreadStateException}}Copy the code
3.2. Implement the Runnable interface
Public implements Runnable{@override public void run() {system.out.println ("Runnable: implements Runnable; "+ Thread.currentThread().getName()); } public static void main(String[] args) { MyRunnable myRunnable = new MyRunnable(); Thread thread = new Thread(myRunnable); thread.start(); New Thread(new Runnable() {@override public void run() { System.out.println(" Anonymous inner class "+ thread.currentThread ().getName()); } }).start(); New Thread(() ->{system.out.println ("lambda: "+ thread.currentThread ().getName())); }).start(); }}Copy the code
3.3. Implement Callable interface (with return value)
Public class MyCallable implements Callable<Long> {// The return value type must be specified. @override public Long Call () throws Exception {return 1+1L; } public static void main(String[] args) {MyCallable MyCallable = new MyCallable(); FutureTask<Long> FutureTask = new FutureTask<>(myCallable); Thread Thread = new Thread(futureTask); thread.start(); Try {system.out.println (" get result: "+futureTask.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); }}}Copy the code

4. Start and stop the thread

4.1. Thread start
  • Interview question: Does the start thread execute the start or run method?
  • Start () method
  • A new thread is created only after the start method is called. The run method is called directly and executed in the main thread
  • Note: Do not call the start method manually. A start method can only be called once by a thread object
4.2. The thread stops
  • Stop method (forcibly stop, lock resources cannot be released, deadlock may cause serious problems, disable)
  • Wait for the run method to finish
  • Interrupts run with a condition

5. Thread sleep

  • Thread.sleep (ms)
  • Once the thread goes to sleep, it gives up the CPU
  • Usage scenario: When performing a large number of tasks, sleep to reduce CPU consumption

6. Background processes

  • Also called daemon thread, Sprite thread
  • To set a thread as background thread:setDaemon(true)
  • The purpose of the daemon thread is to provide services to other threads. Once other threads stop, the daemon thread automatically stops

7. Merge threads

  • The current thread can merge with other threads and perform operations on the current thread when the other threads finish.
  • Note: Two threads cannot merge with each other, otherwise deadlock will occur

8. Thread priority

  • By default, threads are executed preemptively, in no particular order, with different priorities having different probabilities of getting cpus
  • setPriority(int)Set priority. The default value is 5. The value ranges from 1 to 10

The life cycle of a thread

[image upload failed…(image-f8805D-1600949547611)]

  1. New: The object has just been created and start has not yet been called
  2. Ready: a call to start was made, but no CPU was grabbed and cannot be executed
  3. Running: CPU has been grabbed and running
  4. Block: The thread encounters some condition and suspends execution
  5. Death: The run method has finished executing

10. Thread synchronization

10.1. Why do thread synchronization problems occur?
  • Threads are preemptive. When a thread is executing instructions, it may be interrupted by other threads, and data inconsistency may occur
  • Multiple threads operate on a resource simultaneously
10.2 solution to thread synchronization problem (locking mechanism)
  • Synchronized methods

    • grammar

      Public synchronized return type method name (parameter){

      }

    • Once a thread enters the method, it will hold the lock. Other threads cannot enter the method. Other threads can only enter the method when the thread is finished executing.

    • Related interview questions:

      • StringBufferwithStringBuilderThe difference between
      • ArrayListandVectorThe difference between
      • HashMapandHashtableThe difference between
    • Related knowledge points

      • The synchronized method locks this, the current object
      • Locking mechanism: After a lock is placed, the JVM starts the Monitor to Monitor the threads that are entering the code block or method body. If the lock on the method body or method body is owned by a thread, the Monitor will deny access to the code block or method to other threads until the thread that holds the lock completes its execution and releases the lock
      • Once locked, the performance of the program will be reduced
  • Synchronized code block

    • grammar

      Public Return type method name (parameter){… Synchronized {code}… }

    • Pay attention to

      • Any Java Object can be a lock Object
      • Lock objects cannot be local variables
      • Once the thread enters the code block, it locks it, holds the lock object, and releases the lock automatically after executing the code block. Throwing exceptions also releases the lock
    • Compare synchronized methods with synchronized code blocks

      • The synchronous approach is much cleaner
      • The synchronous method has a larger lock granularity (the larger the lock scope is), and the larger the lock granularity is, the worse the performance is. The performance of synchronous code block is higher than that of synchronous method
  • Synchronization lock

    • Present in Java 1.5, in the java.util.concurrent package

    • Lock interface, uppermost interface

    • Subinterfaces: ReadLock, WriteLock, ReadWriteLock

    • Common implementation class: ReentrantLock

    • Create object: Lock Lock = new RentrantLock()

    • Common methods: lock.lock() locks, lock.unlock() releases locks

    • grammar

      lock.lock(); try{ 代码 }finally{ lock.unlock(); }

11. Singleton mode

  • Singleton mode is divided into hunchman and slacker mode to ensure that a class has only one instance object

    • Advantages:
      • Reduce system resource consumption
      • Meet the requirements of some particular business
  • The hungry type

    • The object is created from the start, and memory resources are consumed whether getInstance() is called or not

    • The Runtime in the system is of hungry type

      public class Singleton01 { private static Singleton01 instance = new Singleton01();

      private Singleton01(){
      
      }
      
      private static Singleton01 getInstance(){
          return instance;
      }
      Copy the code

      }

  • LanHanShi

    • GetInstance () creates the object when it is called. Memory is not consumed initially

    • Thread synchronization problem (need to check object null in getInstance() method)

      Public class Singleton02 {private static Singleton02 instance;

      private Singleton02(){
      
      }
      
      private static Singleton02 getInstance(){
          if (instance == null){
              instance = new Singleton02();
          }
          return instance;
      }
      Copy the code

      }

      Public class Singleton06 {private static Singleton06 instance;

      private Singleton06(){
      
      }
      
      private static Singleton06 getInstance(){
          if (instance == null){
              synchronized (Singleton06.class){
                  if (instance == null){
                      instance = new Singleton06();
                  }
              }
          }
          return instance;
      }
      Copy the code

      }

12. Volatile keyword

  • Used to modify variables and improve thread visibility, is a lightweight solution to thread synchronization that guarantees visibility but not atomicity
  • Visibility: The value of a variable is directly available to each thread
  • Atomicity: Code runs as a whole, not divisible
  • With the volatile keyword, a thread reads the value directly from main memory, not from the cache. Changes made by any thread can be seen by other threads
  • The variable is notvolatilemodified
! [Insert picture description here](https://upload-images.jianshu.io/upload_images/24613156-31baa798c52f2d53? imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

Insert a picture description here

  • Variables arevolatilemodified

Thread deadlocks

  • What happens:

    • The lock is not released after being locked
    • Two threads can enter a mutually waiting situation when they both hold the lock that the other needs and need the lock that the other needs

    public class LockTest { private static Object lock1 = new Object(); private static Object lock2 = new Object(); public static void main(String[] args) { Thread thread1 = new Thread(() -> { for (int i = 0; i < 100; i++) { synchronized (lock1){ synchronized (lock2){ System.out.println(“thread1————“+i); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); }}}}}); Thread thread2 = new Thread(()->{ for (int i = 0; i < 100; i++) { synchronized (lock2){ synchronized (lock1){ System.out.println(“thread2————“+i); }}}}); thread1.start(); thread2.start(); }}

Thread wait and notification

  • By calling the lock Object, defined in the Object class

  • Wait: To block a thread

    • wait(): Wait until informed
    • Wait (ms): Wait a specified amount of time for a thread to be notified or woken up automatically
  • Notify: Tells a waiting thread to return from the blocked state to the ready state

    • notify(): Notifies a waiting thread
    • notifyAll(): Notifies all waiting threads
  • Note that only the notify or wait methods can be called on the lock object. You must call this on the lock object of the synchronized code block or on the synchronized method. Otherwise there will be a IllegalMonitorStateException anomalies

What’s the difference between ‘wait’ and ‘sleep’?

  • Wait releases lock resources, sleep does not
  • Sleep is a thread object call, wait is a lock object call;
  • To sleep must wait for the end of the sleep period, and to wait for the end of the sleep period can also be used to wake up

16. Producer-consumer model

  • Not one of the GOF23 design patterns, but a thread-related design pattern

  • Function:

    1. Decouple: Let producer consumers decouple from each other without direct access
    2. High concurrency: producer-consumer decoupling, producers and consumers do not need to wait for each other, and producers can handle more consumer requests
    3. Solve the imbalance between busy and idle: solve the problem of too fast producer speed and too low consumer demand, or too slow producer speed and too big consumer demand
  • Implementation process:

    1. Defines a buffer for storing data with an upper limit
    2. The producer thread stores production data into a buffer, makes the producer wait when the buffer is full, and notifies the producer to continue production if the buffer is not full
    3. The consumer retrieves data from the buffer, and when the buffer is empty, the consumer is told to wait until there is data, notifying the consumer to continue consuming

17. Block the queue

  • Is a collection that blocks automatically based on the number of data
  • BlockingQueue<T>The parent interface
  • Common implementation classes:
    • LinkedBlockingQueueBlocking queue with linked list structure (efficient insertion and deletion)
    • ArrayBlockingQueueArray structure blocking queue (efficient query)
  • Commonly used method
    • put()Add data to the end and block the current thread if it reaches the threshold
    • take()Removes data from the queue header, or blocks if empty

Thread pools

18.1. What are threads for?
  • Recycle thread resources, thread is a very important resource, thread creation and destruction are very consumption of resources, frequent creation and destruction of threads will reduce the performance of the program
  • Note: Threads in the thread pool do not die immediately after performing a task, but return to the pool and can be reused
18.2. Thread Pool API
  • The Executor interface

    • Execute (Runnable)Perform a single thread task
  • The ExecutorService interface

    • showdownClosed:
    • shutdownNow: Shut it down immediately
    • submitSubmitted:
  • ThreadPoolExecutor thread implementation class

  • Executors utility class

    • Helps create different types of thread pools

    • Main methods:

      • ExecutorService newCachedThreadPool() is an unlimited number of threads, with no control over concurrency and higher speed

        / / unlimited length thread pool public static void testCachedThreadPool () {ExecutorService threadPool = Executors. NewCachedThreadPool (); For (int I = 0; i < 10; I++) {threadpool.execute (()->{system.out.println () + thread.currentthread ().getname ()); }); try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } threadPool.shutdown(); }

      • ExecutorService newFixedThreadPool(int) A fixed length thread pool that can control the number of concurrent tasks. If the number of concurrent tasks is large, a queue is required

        / / the length of the fixed thread pool public static void testFixedThreadPool () {ExecutorService threadPool = Executors. NewFixedThreadPool (5); For (int I = 0; i < 10; I++) {threadpool.execute (()->{system.out.println () + thread.currentthread ().getname ()); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); }});

        }
        threadPool.shutdown();
        Copy the code

        }

      • ExecutorService newSingleThreadExecutor() single-threaded thread pool

        / / single thread thread pool public static void testSingleThreadPool () {ExecutorService threadPool = Executors. NewSingleThreadExecutor (); For (int I = 0; i < 10; I++) {threadpool.execute (()->{system.out.println () + thread.currentthread ().getname ()); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); }});

        }
        threadPool.shutdown();
        Copy the code

        }

      • ScheduledExecutorService newScheduledThreadPool(int) Specifies the thread pool that can be scheduled. The execution period and delay can be set

        public static void testScheduleThreadPool(){ ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(10);

        ThreadPool. ScheduleAtFixedRate (() - > {System. Out. Println (" the currently executing is "+ Thread. CurrentThread (). The getName ()); }, 5, 1, TimeUnit. SECONDS); //threadPool.scheduleWithFixedDelay()Copy the code

        }

  • Custom thread pools

    • Construction method:ThreadPoolExector
    • Core threads:corePoolSize
    • Maximum threads:maximumPoolSize
    • Survival time:keepAliveTime
    • Time unit:timeUnit
    • Block queue, save execution task (Runnable) :workingQueue
    • Optimizing the allocation of
      1. The core thread configuration, like the maximum number of threads, reduces the overhead of creating new threads and destroying them
      2. Number of core threads configuration andcpuThe number of cores is related. The number of cores * N (N >= 1) N depends on the task quantity and execution time
      3. Blocking queue usageLinkedBlockingQueue, add and delete tasks efficiently

    public static void myselfThreadPool(){ int processors = Runtime.getRuntime().availableProcessors(); System.out.println(processors); int n = 2; ThreadPoolExecutor threadPool = new ThreadPoolExecutor(processors * n, processors * n, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue()); for (int i = 0; i < 10; I++) {threadpool.execute (()->{system.out.println () + thread.currentthread ().getname ());

            });
    
        }
        threadPool.shutdown();
    }
    Copy the code

19, ThreadLocal

19.1. What is ThreadLocal?
  • The purpose of ThreadLocal is to provide local variables within a thread that operate for the lifetime of the thread, reducing the complexity of passing some common variables between functions or components within the same thread.
19.2. The difference between Syncronized and ThreadLocal?
  • Syncronized can solve the problem of variable isolation between threads by denying access from other threads after a thread is locked. Currently, only one thread is accessing the resource. However, this method requires locking each thread, which reduces the efficiency and concurrency of the program
  • Syncronized is a time-for-space method that queues all threads for access and provides only one variable, focusing on synchronization of access resources between multiple threads
  • ThreadLocal does not require locking, but also provides isolation of variables between threads, allowing for high concurrency. Variables are only used for the lifetime of the thread
  • ThreadLocal provides a separate copy for each thread by exchanging space for time. Each thread accesses its own variable without interfering with each other. Using ThreadLocal can ensure higher concurrency of programs.
19.3. What are the advantages of ThreadLocal?
  • Binding parameters: Store each thread’s binding data, which can be retrieved where needed, avoiding code coupling problems associated with passing parameters directly
  • Thread isolation: Data between threads is isolated and concurrent, avoiding performance loss caused by synchronous methods
19.4. Usage Scenarios of ThreadLocal
  • When JDBC connects to a database and obtains a Connection, to ensure transaction operations under high concurrency, ensure that the object obtained in dao layer getConnection() is the same object as the transaction’s Connection object. You need to use ThreadLocal to isolate data between threads without affecting database connection performance.
  • When connection is empty, use the database connection pool to fetch a connection object and save the connection object to ThreadLocal. After the transaction is committed, the connection object bound by the current thread needs to be unbound.threadLocal.remove(), the goal is to avoid memory leaks
! [Insert picture description here](https://upload-images.jianshu.io/upload_images/24613156-95100fd63efb7a3a? imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)