Detailed introduction to Java threads and Java multithreading

Table of contents

1. The difference between process and thread

   1.1 Process

   1.2 Threads

2. Concurrency and parallelism

   2.1 Parallel

   2.2 Concurrency

   2.3 Monitor the execution of threads

3. How to create

3.1 Inheriting the Thread class          

Thinking: Why not call the start() method directly through the object?

3.2 Implement the Runnable interface

3.3 Using Callable to create threads

3.4 Difference between Callable and Runnable

The difference between inheriting Thread and implementing the Runnable interface

3.5 Use thread pool such as Executor framework

3.5.1 Concept

3.5.2 Benefits

3.5.3 Basic Principles of Thread Pool Execution

3.5.4 Thread pool creation method

3.5.5 Classification of thread pools

3.5.6 Core parameters of the thread pool

4. Common methods

Five, multi-threaded implementation

6. Thread termination

7. Common methods

 Eight, thread life cycle

8.1 Thread state

8.2 Wait(), notify(), notifyAll() analogy

Nine, thread safety

 9.1 Reasons for security issues​Edit

 9.2  synchronized

  9.3 Lock

  9.4 Thread locks

  9.5 Concurrent tool class ConcurrentHashMap HashMap HashTable

           9.6 Thread deadlock

           9.7 Release lock

10. Thinking questions

1. The volatile keyword

2. Is count++ an atomic operation?

3. How to ensure atomic operations

4. The principle of atomic class -- CAS principle

5. The difference between ConcurrentHashMap HashMap and HashTbale



1. The difference between process and thread


   1.1 Process

        The software running in the operating system, such as the QQ we use, starts a process, and the operating system allocates a new memory space for the process. The process is independent, dynamic and concurrency

  1. Independence: A process is a basic unit that can run independently, and it is also an independent unit for the system to allocate resources and schedule
  2. Dynamics: The essence of a process is an execution process of a program, a process is dynamically generated, and dynamic is dying
  3. Concurrency: Any process can execute concurrently with other processes

   1.2 Threads

        A thread is created by a process and is an entity of the process. A process can have multiple threads. Is a single sequential flow of control in a process, a path of execution. That's what the application does.     For example : anti         - virus in 360 software, scanning
        Trojans             ,
            and             cleaning
        garbage Ending         the daemon thread by notification             generally serves the worker thread. When all user threads end, the daemon thread ends automatically. The common daemon thread has a garbage collection mechanism application: if we hope that when the                 main thread ends, the child thread will automatically end At the end, you only need to set the child thread as a daemon thread. Setting method instance.setDaemon(), before instance.start()     Note: a process includes at least one thread







2. Concurrency and parallelism

  2.1 Parallel

        At the same time, multiple instructions are executed on multiple CPUs at the same time,
        causing a seemingly simultaneous illusion. Simply put, the multitasking achieved by a single-core CPU is parallelism.

  2.2 Concurrency

        At the same time, multiple instructions are executed alternately on multiple CPUs. Multi-
        core CPUs can execute parallel
    Notes: concurrency and parallelism can occur at the same time

  2.3 Monitor the execution of threads

      Enter Jconsole in the terminal to monitor the execution of the thread

3. How to create

3.1 Inheriting the Thread class



               

         After inheriting the Thread class, the class can be used as a thread. It is often necessary to rewrite run() (Thread implements the Runnable interface), write your own business logic in this method, and create an instance of this class for operation, and call the start method through the instance.

Thinking: Why not call the start() method directly through the object?


    When we run a program, it is equivalent to starting a thread. When the process starts, a main thread is opened in the process. When the main thread executes the instance.start(), the main thread will not block and will continue to execute. If you call directly run(), run() at this time is an ordinary method, it will block, and no real thread is opened, and other statements will be executed only after run() is executed. It is the native method start0() instead of run() that really realizes the effect of multithreading. Note that start0() is called by the JVM, and the bottom layer is implemented by c/c++ (the main thread will end after executing the task, but when there are sub-threads running, the process will not end. When all threads end, process is over)

3.2 Implement the Runnable interface

    Notes: Java is single-inherited. In some cases, a class may have inherited a certain parent class. It is obviously impossible to create a thread by inheriting the method of the Thread class. Therefore, Java designers provide another method to create a thread, which is to implement the Runnable interface to implement the method. A new thread
    needs to be created, and the instance of the class that implements the Runnable interface method is put into the thread's parameterized method. Here is the use Proxy pattern for design patterns.

3.3 Using Callable to create threads

    Unlike the Runnable interface, the Callable interface provides a call() method as a thread execution body. The call() method is more powerful than the run() method.

3.4 Difference between Callable and Runnable

  1.   The call() method can have a return value
  2.   The call() method can declare to throw exceptions. The run method in the callable interface implementation class allows exceptions to be thrown upwards, which can be handled internally, try catch, but the exceptions of the run method in the runnable interface implementation class must be handled internally and cannot be thrown

        Both callable and runnable can be applied to executors. The thread class only supports runnable,

The difference between inheriting Thread and implementing the Runnable interface

  1.  From the perspective of java design, there is essentially no difference in creating threads by inheriting Thread or implementing the Runnale interface. Thread essentially implements the Runnable interface.
  2.  The way to implement the Runnbale interface is more suitable for the situation where multiple threads share a resource, and avoids the limitation of single inheritance

3.5 Use thread pool such as Executor framework


    3.5.1 Concept

       A container for threads, a pool for threads

    3.5.2 Benefits

       1. Reduce the operation of frequently creating and destroying threads, saving resources
       2. The thread pool will process idle threads to achieve thread reuse

    3.5.3 Basic Principles of Thread Pool Execution

      1. Create a pool, there is no thread at this time pool.getPoolSize()
      2. When the task is submitted to the thread pool for the first time, the thread pool will create a thread to execute the task. When the task is executed. The thread object returned to the pool thread will not die.
      3. When the task is submitted again, the thread pool will use the idle thread to process the task. If there is no idle thread, a new thread will be created

    3.5.4 Thread pool creation method

        Create a thread pool
             ExecutorService pool = Executors.newCachedThreadPool();
             The thread pool can create up to int maximum threads
            ExecutorService pool = Executors.newFixedThreadPool(3);
             Create a thread pool object, specify the maximum number
            to create a thread pool, and create new threads as needed , but will reuse previously constructed threads when available.
        Way one
           1. Create a task object
                MyTarget myTarget = new MyTarget();
           2. Submit tasks to the thread pool
                pool.submit(myTarget);
                the past way Thread t1 = new Thread( myTarget);
               Disadvantages: Create threads by yourself, execute tasks, die and waste resources, and system resource overhead is high
           3. If you don’t need the thread pool, close it
                pool.shutdown();
        Method 2

            anonymous inner class

3.5.5 Classification of thread pools

3.5.6 Core parameters of the thread pool

1. int corePoolSize

      Thread pool core thread size, if your number of tasks is less than the number of core threads, then the number of open threads is still three

2.int maximumPoolSize

      The maximum number of threads in the thread pool, which will be destroyed based on KeepaliveTime

3.KeepaliveTime

      Idle thread lifetime

4. TimeUnit time unit

      Time unit, specify the time unit for keepAliveTime 

5.workQueue blocking queue, blocking queue for saving tasks

        1). ArrayBlockQueue Array-based bounded queue, FIFO, to prevent resource exhaustion

        2). LinkedBlockQueue is an unbounded blocking queue based on linked list, the boundary value is Integer.MAX FIFO

                        Tips: The maximumPoolSize parameter is useless

        3). SynchronousBlockQueue (no cache task queue)

                        Tips: The maximumPoolSize parameter is useful, if it is exceeded, the rejection strategy will be executed

        4). ProprityBlockQueue() Comparator implementation in several areas, comparing unbounded blocking queues

6.ThreadFactory

        Engineering classes that create threads, such as daemon threads

7. RejectedExecutionHandler handler rejection strategy

        1). callerrunsPolicy (unless the thread pool is shutdown, the task is discarded)

        2). AbortPolicy (directly throw an exception)

        3). DiscardPolicy (Do nothing, discard the task directly) //Not recommended

        4). DiscardOldestPolicy (do nothing, directly discard the earliest task in the queue)

4. Common methods

User thread: also called worker thread, when the task of the thread is executed or ends by notification

Daemon thread: generally serves the worker thread. When all user threads end, the daemon thread ends automatically

Common Daemon Threads: Garbage Collection Mechanism

Five, multi-threaded implementation

 6. Thread termination

 7. Common methods

Eight, thread life cycle

8.1 Thread state

 8.2 Wait(), notify(), notifyAll() analogy

Nine, thread safety

 9.1 Reasons for security issues

solution

1. Synchronized code block

2. Synchronization method

3.Lock lock

9.2  synchronized

1. In the Java language, the concept of object mutex is introduced to ensure the integrity of shared data operations.

2. Each object corresponds to a tag that can be called a mutex. This tag is used to ensure that only one thread can access the object at any time.

3. The keyword sychronized is used to associate with the mutex of the object. When an object is modified with sychronized, the object can only be accessed by one thread at any time.

4. The limitation of synchronization: the execution efficiency of the program will be reduced

5. The lock of the synchronization method (non-static) can be this or other objects (required to be the same object)

6. The lock of the synchronization method (static) is the current class itself

Detailed explanation of the role and usage of static in Java_CrazyCodeBoy's blog-CSDN blog_java static

 Member variables and member methods modified by static are independent of any objects of this class. That is, it does not depend on a class-specific instance and is shared by all instances of the class. As long as this class is loaded, the Java virtual machine can find them by default in the method area of ​​the runtime data area according to the class name. Therefore, a static object can be accessed before any of its objects are created, without referencing any objects.

The attribute or method modified by the static keyword does not belong to the instantiated object, but belongs to the class, and this belongs to the instance object of the current operation, so the synchronization static lock is on the class

public class demoSell{
    //静态方法
    public synchronized static void method1(){

    }
    //静态方法中的同步代码块
    public static void mehtod2(){
        synchronized(demoSell.class){
            
        }
    }
}

Notice:

1. If the synchronization method is not modified with static: the default object is this

2. If the method uses static modification, the default lock object: current class.class

3. Implementation steps

       Need to analyze the locked code first

       Select a synchronized code block or a synchronized method

        Require multiple thread lock objects to be the same

1. Synchronized code block

synchronized(对象){//得到对象的锁,才能操作同步代码块
//需要被同步代码
}

2. synchronized can also be placed in the method declaration, indicating that the entire method is a synchronized method

public synchronized void method(String name){
//需要被同步的代码
}

9.3 Lock

//创建可重复锁
Lock lock = new ReentrantLock();
//上锁
lock.lock();
//代码块
.............
//释放锁
lock.unlock();

 9.4 Thread locks

9.5 Concurrent tool class ConcurrentHashMap HashMap HashTable

9.6 Thread deadlock

concept:

Multiple threads occupy each other's lock resources, but refuse to give in, resulting in a deadlock. In programming, deadlock must be avoided.

9.7 Release lock

1. The synchronization method of the current thread, after the synchronization code block is executed, the lock will be released automatically

2. The current thread encounters break and return in the synchronization code block and synchronization method

3. The current thread has an unhandled Error or Exception in the synchronization code block or synchronization method, resulting in an abnormal end

4. The current thread executes the wait() method of the thread object in the synchronization code block and synchronization method, the current thread pauses and releases the lock

Note: the following cases will not release the lock

1. When a thread executes a synchronization code block or a synchronization method, the program calls the Thread.sleep() and Thread.yield() methods to suspend the execution of the current thread without releasing the lock.

2. When a thread executes a synchronization code block, other threads call the suspend() method of the thread to suspend the thread. The thread will not release the lock. You should avoid using suspend() and resume() to control the thread. The method is no longer Recommended Use.

10. Thinking

1. The volatile keyword

In the case of multi-threading, the visibility of data is guaranteed, and the attribute of volatile is added. After one thread modifies, another thread can also see it

Principle: When a thread modifies the data, it will refresh the data to the main memory, and the copies read by other threads will become invalid, and the new data in the main memory will be read again

2. Is count++ an atomic operation?

No, three steps:

1. Store the value of count in the main memory to line A into a unique space

2. Execute the +1 operation in the unique workspace of the thread

3. Refresh the relaod of 101 into the main memory

The execution right of the CPU may be lost at any time, for example, it is preempted by other thread B before the +1 operation is refreshed to the main memory

3. How to ensure atomic operations

1. Synchronized code block

2. Atomic class AtomicInteger

4. The principle of atomic class -- CAS principle

When modifying the value in the main memory, first judge with the old value and the value in the main memory

        If equal, modify directly

        If it does not wait, it means that other threads have modified it, and it is necessary to re-acquire the new value in the main memory

There are three variables involved

1. Old value: When the value in the main memory is obtained for the first time, it is stored in this variable as the old value, such as 100

2. The new value is the value after the thread operation, such as 101 after executing the ++ operation

3. The value to be modified is the value in the main memory

If the old value is equal to the value to be modified, it means that it has not been modified and can be directly assigned

5. The difference between ConcurrentHashMap HashMap and HashTbale

HashMap is the most efficient but not safe

HashTable is the least efficient and safe, and each method is locked

ConcurrenetHashp is the second most efficient and safe

Guess you like

Origin blog.csdn.net/Doreamonx/article/details/125218129
Recommended