What is JUC
Introduction to JUC
In Java, the thread part is a key point. The JUC mentioned in this article is also about threads. JUC is the abbreviation of java.util.concurrent toolkit. This is a toolkit for processing threads, which began to appear in JDK1.5
Processes and threads
- A process is an operation or movement of a computer program about a data set three. It is the basic unit for the system to allocate and schedule resources and the basis of the operating system interface. In the contemporary computer architecture of thread oriented design, a process is the container of threads. A program is the description of instructions, data and their organizational forms, A process is the entity of a program. It is a running activity of a program on a data set in a computer. It is the basic unit for the system to allocate and schedule resources. It is the basis of the structure of the operating system. A program is the description of instructions, data and their organizational form. A process is the entity of a program
- Thread is the smallest unit that the operating system can calculate. It is contained in the process and is the actual operation unit in the process. A thread refers to a single sequential control flow in the process. Multiple threads can be concurrent in a process, and each thread performs different tasks in parallel
In summary:
- Process: refers to an application running in the system; A single run of a program is a process; Once the program is carried out, it is a process; Process ---- the smallest unit of resource allocation
- Thread: the basic unit in which the system allocates processor time resources, or a unit execution flow executed independently within a process. Thread ---- the smallest unit of program execution
Status of the thread
Thread state enumeration type
Thread.State
public enum State { /** * ((New) * Thread state for a thread which has not yet started. */ NEW, /** * ((ready) * Thread state for a runnable thread. A thread in the runnable * state is executing in the Java virtual machine but it may * be waiting for other resources from the operating system * such as processor. */ RUNNABLE, /** * (Blocking) * Thread state for a thread blocked waiting for a monitor lock. * A thread in the blocked state is waiting for a monitor lock * to enter a synchronized block/method or * reenter a synchronized block/method after calling * {@link Object#wait() Object.wait}. */ BLOCKED, /** * ((see you or leave) * Thread state for a waiting thread. * A thread is in the waiting state due to calling one of the * following methods: * <ul> * <li>{@link Object#wait() Object.wait} with no timeout</li> * <li>{@link #join() Thread.join} with no timeout</li> * <li>{@link LockSupport#park() LockSupport.park}</li> * </ul> * * <p>A thread in the waiting state is waiting for another thread to * perform a particular action. * * For example, a thread that has called <tt>Object.wait()</tt> * on an object is waiting for another thread to call * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on * that object. A thread that has called <tt>Thread.join()</tt> * is waiting for a specified thread to terminate. */ WAITING, /** * (Obsolete (not waiting) * Thread state for a waiting thread with a specified waiting time. * A thread is in the timed waiting state due to calling one of * the following methods with a specified positive waiting time: * <ul> * <li>{@link #sleep Thread.sleep}</li> * <li>{@link Object#wait(long) Object.wait} with timeout</li> * <li>{@link #join(long) Thread.join} with timeout</li> * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li> * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li> * </ul> */ TIMED_WAITING, /** * ((end) * Thread state for a terminated thread. * The thread has completed execution. */ TERMINATED; }
The difference between wait and sleep
- sleep is the static method of Thread and wait is the method of Object. It can be called on any Object instance
- sleep will not release the lock, nor does she need to occupy it. wait will release the lock, but the premise for calling it is that the current thread occupies the lock (that is, the code should be in synchronized)
- They will be interrupted by the interrupted method, and they all have a feature that they will wake up wherever they sleep
Parallel and serial
Serial mode
Serial means that all tasks are carried out in sequence one by one. Serial means that a truck of firewood must be loaded before it can be transported. Only when it is transported, can the truck of firewood be unloaded, and only after the whole three steps are completed, can the next step be carried out
Serial is to get only one task at a time and execute this task
Parallel mode
Parallelism means that multiple tasks can be obtained and executed at the same time. The parallel mode is equivalent to dividing a long queue into multiple short queues, so parallelism shortens the length of the task queue. The efficiency of parallelism depends strongly on multi-process / multi-threaded code from the code level and multi-core CPU from the hardware point of view
Concurrent
**Concurrency refers to the phenomenon that multiple programs can run at the same time. More specifically, multiple processes can run at the same time or multiple instructions can run at the same time. * * but this is not the focus. When describing concurrency, we will not deduct whether this word is accurate. The focus of concurrency is that it is a phenomenon. Concurrency describes the phenomenon of multiple processes running at the same time, but in fact, For a single core CPU, only one thread can run at a time, so "running at the same time" here does not mean that there are multiple threads running at the same time. This is a parallel concept, but provides a function to make users see that multiple programs are running at the same time, but in fact, the processes in these programs do not occupy the CPU all the time, but confidently stop for a while
To solve the problem of large concurrency, large tasks are usually decomposed into multiple small people. Because the scheduling of the operating system is random, after being divided into multiple small tasks, they may be executed from any small task, which may lead to some phenomena:
- It may happen that a small task has been executed many times and the next task has not started. Generally, queues or similar data will be used to store the results of each small task
- It is possible to execute the second step before preparing for the first step. This is generally in the form of multiplexing or asynchronous. For example, a task can be executed only when it is ready to generate a time notification
- These little people can be executed in a multi process / multi thread manner, or in a single process / thread. At this time, it is likely to cooperate with multiplexing to achieve high efficiency
Summary
Concurrency: multiple threads are accessing the same resource at the same time, and multiple threads are connected to one point
Example: Spring Festival transportation ticket grabbing e-commerce spike
Parallel: multiple tasks are executed together and then summarized
Example: Boil instant noodles in an electric kettle, tear the seasoning and pour it into the bucket
Tube side
The so-called lock in monitor > java ensures that only one process is active in the process at the same time, that is, the operations defined in the process are called by only one process at the same time (implemented by the compiler), but this does not ensure that the process is executed in the designed order
Synchronization in JVM is realized by entering and exiting management objects. Each object will have a management object, which will be created and destroyed together with Java objects
The execution thread must first hold the pipe process object before executing the method. When the method is completed, the pipe process will be released. The method will hold the pipe process during execution, and other threads can no longer obtain the same pipe process
User thread and daemon thread
User thread: ordinary thread and user-defined thread used at ordinary times
Daemon thread: running in the background, it is a special thread, such as garbage collection
When the main thread ends, the user thread is still running and the JVM survives
If there are no user threads, they are all daemon threads, and the JVM ends
Example: if we do not set the daemon thread
public class Main { public static void main(String[] args) { Thread t = new Thread(() -> { // The isDaemon method is used to determine whether it is a daemon thread. If false is returned, it means it is not a daemon thread System.out.println(Thread.currentThread().getName() + "::" + Thread.currentThread().isDaemon()); while (true) { } }, "t"); t.start(); System.out.println(Thread.currentThread().getName() + "::" + "over"); } } /********************* Console information*************************/ Connected to the target VM, address: '127.0.0.1:50636', transport: 'socket' main::over t::false // At the same time, the program did not end, because although the main thread ended, the t thread did not end
Example: if we set thread t as a daemon thread
public class Main { public static void main(String[] args) { Thread t = new Thread(() -> { // The isDaemon method is used to determine whether it is a daemon thread. If false is returned, it means it is not a daemon thread System.out.println(Thread.currentThread().getName() + "::" + Thread.currentThread().isDaemon()); while (true) { } }, "t"); // Set daemon thread t.setDaemon(true); t.start(); System.out.println(Thread.currentThread().getName() + "::" + "over"); } } /********************* Console information*************************/ Connected to the target VM, address: '127.0.0.1:50636', transport: 'socket' main::over t::true Disconnected from the target VM, address: '127.0.0.1:50636', transport: 'socket' // The program ends because there are no other running threads except the daemon thread