Threads and processes
Threads, processes, if you can not use a word out technology, not solid!
- Process: a program, a collection of QQ.exe Music.exe programs;
- A process can often contain multiple threads, at least one!
- Java has 2 threads by default? main,GC
- Thread: open a process Typora, write, and save automatically (the thread is responsible)
- For Java, it provides Thread, Runnable and Callable operation threads.
Process: each process has an independent code and data space (process context). Switching between processes will have a large overhead. A process contains 1 – n threads. (process is the smallest unit of resource allocation)
**Threads: * * threads of the same type share code and data space. Each thread has an independent running stack and program counter (PC). Thread switching overhead is small. (threads are the smallest unit of cpu scheduling)
Can Java really start threads? The answer is: no!
public synchronized void start() { /** * This method is not invoked for the main method thread * or "system" group threads created/set up by the VM. Any new * functionality added to this method in the future may have to * also be added to the VM.A zero status value corresponds to * state "NEW". */ if (threadStatus != 0) throw new IllegalThreadStateException(); /* * Notify the group that this thread is about to be started * so that it can be added to the group's list of threads * and the group's unstarted count can be decremented. */ group.add(this); boolean started = false; try { start0(); started = true; } finally { try { if (!started) { group.threadStartFailed(this); } } catch (Throwable ignore) { /* do nothing. If start0 threw a Throwable then it will be passed up the call stack */ } } } // Local methods, the underlying operation is C + +, Java can not directly operate the hardware private native void start0();
Concurrent, parallel
Concurrent programming: concurrent, parallel
Concurrency: it means that only one instruction can be executed at the same time, but multiple process instructions are executed in rapid rotation, which has the effect of simultaneous execution of multiple processes in the macro, but not in the micro. It just divides the time into several segments to make multiple processes execute quickly and alternately.
Parallel: multiple instructions are executed simultaneously on multiple processors at the same time. Therefore, both are implemented together from the micro and macro point of view.
Concurrency (multiple threads operate on the same resource)
- One core CPU simulates multiple threads and alternates quickly.
Parallel (multiple people walking together)
- Multi core CPU, multiple threads can execute at the same time; eg: thread pool!
public class Test1 { public static void main(String[] args) { // Gets the number of cores of the cpu // CPU intensive, IO intensive System.out.println(Runtime.getRuntime().availableProcessors()); // If the computer is 8-core, the result is output 8 } }
The essence of concurrent programming: making full use of CPU resources
Threads have several states (6)
public enum State { /** * Thread state for a thread which has not yet started. * Thread newborn state */ NEW, /** * 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. * Thread running */ RUNNABLE, /** * 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}. * Thread blocking status */ BLOCKED, /** * 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. * Thread waiting state, dead, etc */ 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> * Thread timeout waiting state. It will not wait for a certain time */ TIMED_WAITING, /** * Thread state for a terminated thread. * The thread has completed execution. * Thread termination status indicates that the thread has completed execution */ TERMINATED;}
\1. New: a new thread object is created.
\2. Runnable: after the thread object is created, other threads (such as main thread) call the start() method of the object. The thread in this state is located in the runnable thread pool and waits to be selected by thread scheduling to obtain the cpu usage right.
\3. Running: the runnable thread obtains the cpu time slice and executes the program code.
\4. Blocked: the blocked state refers to that the thread gives up the cpu usage right for some reason, that is, it gives up the cpu timeslice and temporarily stops running. The thread will not have the opportunity to get the cpu timeslice to the running state again until it enters the runnable state. There are three kinds of blocking conditions:
(1) . wait blocking: the running thread executes the o.wait() method, and the JVM will put the thread into the waiting queue.
(2) . synchronization blocking: when a running thread obtains the synchronization lock of an object, if the synchronization lock is occupied by another thread, the JVM will put the thread into the lock pool.
(3) . other blocking: when a running thread executes the Thread.sleep(long ms) or t.join() method, or makes an I/O request, the JVM will set the thread to the blocking state. When the sleep() state times out, the join() waits for the thread to terminate or time out, or the I/O processing is completed, the thread will return to the runnable state.
\5. Dead: when the execution of the thread run() and main() methods ends, or the thread exits the run() method due to an exception, the thread ends its life cycle. The dead thread cannot be reborn again.
1, Thread state diagram
2, Initial state
- Implementing runnable and callable interfaces and inheriting Thread can get a Thread class. When a new instance comes out, the Thread enters the initial state
3, Operational status
- The runnable state only means that you are qualified to run. If the scheduler does not select you, you will always be runnable.
- Call the start() method of the thread, and the thread enters the runnable state.
- The sleep() method of the current thread ends, and the join() of other threads ends. Wait for the user to input. When a thread gets the object lock, these threads will also enter the runnable state.
- When the time slice of the current thread is used up, call the yield() method of the current thread, and the current thread enters the runnable state.
- After the thread in the lock pool gets the object lock, it enters the runnable state.
4, Running status
- The state of a thread when the thread scheduler selects a thread from the runnable pool as the current thread. This is also the only way for a thread to enter the running state.
5, Death state
- When the thread's run() method is completed, or the main() method of the main thread is completed, we think it is dead. The thread object may be alive, but it is no longer a separate thread. Once a thread dies, it cannot regenerate.
- Calling the start() method on a dead thread will throw a java.lang.IllegalThreadStateException.
6, Blocking state
- The current thread T calls the Thread.sleep() method, and the current thread enters the blocking state.
- Other threads running in the current thread t2 call the join() method, and the current thread enters the blocking state.
- While waiting for user input, the current thread enters a blocking state.
7, Wait queue (this is a method in Object, but it affects threads)
- ==Before calling obj's wait(), notify() method, you must obtain the obj lock, that is, you must write it in the synchronized(obj) code segment. = = not now
- Steps and diagrams related to waiting queues
- Thread 1 obtained the lock of object A and is using object A.
- Thread 1 calls the wait() method of object A.
- Thread 1 releases the lock of object A and immediately enters the waiting queue.
- The objects in the lock pool compete for the lock of object A.
- Thread 5 obtains the lock of object A, enters the synchronized block, and uses object A.
- Thread 5 calls the notifyAll() method of object A to wake up all threads and all threads enter the lock pool. ||||| thread 5 calls the notify() method of object A to wake up A thread. It is unknown who will be awakened. The awakened thread enters the lock pool.
- When synchronized ends where the notifyAll() method is located, thread 5 releases the lock of object A.
- The threads in the lock pool compete for the object lock, but when thread 1 can grab it is unknown. ||||| the original lock pool + the awakened threads in step 6 compete for the object lock together.
8, Lock pool status
- When the current thread wants to call the synchronization method of object A, it finds that the lock of object A is occupied by another thread. At this time, the current thread enters the lock pool state. In short, the lock pool contains threads that want to compete for object locks.
- When a thread 1 is awakened by another thread 2, thread 1 enters the lock pool state to compete for the object lock.
- Lock pool is a concept only available in a synchronous environment. An object corresponds to a lock pool.
9, Comparison of several methods
- Thread.sleep(long millis). This method must be called by the current thread. The current thread enters blocking without releasing the object lock. After millis, the thread automatically wakes up and enters the runnable state. Function: the best way to give other threads the opportunity to execute.
- Thread.yield(), which must be called by the current thread. The current thread abandons the obtained cpu time slice and changes from the running state to the runnable state, allowing the OS to select the thread again. Function: * * let threads with the same priority execute in turn, but it is not guaranteed that they will execute in turn. In practice, yield () cannot be guaranteed to achieve the purpose of concession, because the concession thread may be selected again by the thread scheduler** Thread.yield() does not cause blocking.
- t.join()/t.join(long millis). The current thread calls the join method of other thread 1. The current thread blocks, but does not release the object lock. Until thread 1 finishes executing or the millis time expires, the current thread enters the runnable state.
- obj.wait(), the current thread calls the wait() method of the object. The current thread releases the object lock and enters the waiting queue. Wake up automatically depending on notify()/notifyAll() or wait(long timeout)timeout.
- obj.notify() wakes up a single thread waiting on this object monitor. The selection is arbitrary. notifyAll() wakes up all threads waiting on this object monitor.
Thread status:
Threads are always in one of the following five states from creation, running to end: new state, ready state, running state, blocking state and death state.