JAVA concurrent knowledge base

  1. Thread class inheritance

The Thread class is essentially an instance that implements the Runnable interface and represents an instance of a Thread. The only way to start a Thread is through the start() instance method of the Thread class. The start() method is a native method that starts a new line and executes the run() method.

If you cannot extend Thread directly if your class already extends another class, you can implement a Runnable interface.

Tasks with a return value must implement the Callable interface, and similarly, tasks with no return value must implement the Runnable interface. After executing the Callable task, you can retrieve a Future Object. Call get on this Object to retrieve the Object returned by the Callable task. Combine that with the thread pool interface to implement the legendary multithreading that returns results.

  1. newCachedThreadPool

Create a thread pool that can create new threads as needed, but reuse previously constructed threads as they become available. For programs that perform many short-term asynchronous tasks, these thread pools can often improve program performance. Calling execute reuses previously constructed threads (if available). If no existing thread is available, a new thread is created and added to the pool. Terminates and removes threads from the cache that have not been used for 60 seconds. Therefore, a thread pool that remains idle for a long time does not use any resources.

  1. newFixedThreadPool

Create a reusable thread pool with a fixed number of threads to run in a shared unbounded queue. At any given point, most nThreads threads will be active for processing tasks. If the attached task is submitted while all threads are active, the attached task will wait in the queue until there are available threads. If any thread terminates due to failure during execution prior to closure, a new thread will replace it to perform subsequent tasks (if needed). Threads in the pool will remain in existence until a thread is explicitly closed.

  1. newScheduledThreadPool

Create a thread pool that can schedule commands to run after a given delay or to execute them periodically.

Iv. Thread lifecycle (State)

When a thread is created and started, it is neither in the execution state as soon as it is started nor always in the execution state. In its life cycle, a thread passes through five states: New, Runnable, Running, Blocked, and Dead. Especially when a thread is started, it cannot always “hog” the CPU and run on its own, so the CPU has to switch between threads, so the thread state will switch between running and blocking many times

  1. NEW State (NEW)

When a program creates a thread using the new keyword, the thread is in the new state, where the JVM allocates memory and initializes the values of its member variables

  1. Ready (RUNNABLE) :

When the thread object calls the start() method, the thread is in the ready state. The Java virtual machine creates a method call stack and a program counter for it to wait for the schedule to run.

  1. RUNNING status:

If a thread in the ready state acquires the CPU and begins executing the thread body of the run() method, it is running.

  1. BLOCKED:

A blocked state is when a thread gives up CPU usage for some reason, giving up CPU timeslice and temporarily stops running. Until the thread enters the runnable state, it has no chance to get the CPU timeslice again and go to the running state. There are three types of blocking:

Wait block (O.wait -> Wait column) :

The running thread executes the O.wait () method and the JVM places the thread in waitting queue.

Synchronous blocking (lock-> lock pool)

When a running thread obtains a lock on an object that is held by another thread, the JVM adds the lock to the lock pool.

Other blocking (sleep/join)

When a Thread running executes thread.sleep (long ms) or t.join(), or makes an I/O request, the JVM puts the Thread in a blocked state. When the sleep() state times out, when the join() wait thread terminates or times out, or when I/O processing is complete, the thread returns to the runnable state.

  1. Thread DEAD

A thread ends in one of three ways, and then dies.

The end of the normal

  1. The run() or call() method completes, and the thread terminates normally.

Abnormal end

  1. The thread throws an uncaught Exception or Error.

Call the stop

  1. Terminate the thread by calling its stop() method directly – this method is usually deadlocked and is not recommended.

  1. Normal operation end

When the program ends, the thread ends automatically.

  1. Exit the thread with the exit flag

The thread normally terminates after the run() method is executed, however, often some threads are server threads. They take a long time to run and can only be shut down if some external condition is met. Use a variable to control the loop, for example: The most direct way is to set a Boolean flag and control whether the while loop exits by setting this flag to true or false. Example of this code:

We define an exit flag, exit. When exit is true, the while loop exits, and exit defaults to false. The Java keyword volatile is used to define exit. The purpose of this keyword is to synchronize exit, meaning that only one thread can modify the value of exit at a time.

  1. The Interrupt method terminates a thread

There are two ways to interrupt a thread with the interrupt() method:

  1. A thread is blocked: a thread is blocked when sleep, wait, receiver,accept, etc. are used on the socket. InterruptException is thrown when the thread’s interrupt() method is called. The method in the block throws the exception, catches it in code, and breaks out of the loop, giving us a chance to end the thread. Many people believe that calling InterruptedException will terminate the thread, but this is not true. You must catch InterruptedException and then break out of the loop to terminate the run method properly.

  2. The thread is not blocked: Use isInterrupted() to determine the thread’s interrupt flag to exit the loop. When the interrupt() method is used, the interrupt flag is set to true, in the same way that custom flags are used to control loops.

Thread stop() can be used to forcibly terminate a thread, but the stop method is very dangerous. It is like turning off the power of the computer suddenly instead of following the normal procedure. When thread.stop() is called, the thread that created the child thread raises a ThreadDeatherror error and releases any locks held by the child thread. Any block of code that locks is used to protect data consistency. If a call to Thread.stop () results in the sudden release of all locks held by the thread, the protected data may become inconsistent, and other threads may use the corrupted data. It can lead to some very strange application errors. Therefore, using the stop method to terminate a thread is not recommended.

Welcome everyone likes to follow forward comments to discuss together. Will bring you one or two knowledge points every day, grow together