We know that a process corresponds to a group of PCBs. In the operating system kernel, PCBs are divided into ready queues and blocking queues, and are managed using a doubly linked list.
Threads have six states
NEW: The operating system kernel has not created a thread;
Terminated: The thread has finished running and has been destroyed.
Runnable: The thread is in ready state: 1. Already running on the CPU; 2. In the ready queue
Blocked: This is a call to Sleep;
waiting: the wait method is called
timed-waiting: thread calls sleep
The first three states are the main states; the latter three states are blocking states for various reasons. The corresponding code is as follows:
public class Demo13 {
public static void main(String[] args) throws InterruptedException {
Thread thread=new Thread(()->{
System.out.println("thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println(thread.getState());//未创建线程的状态
thread.start();//启动线程
Thread.sleep(500);
System.out.println(thread.getState());
thread.join();//调用后结束线程
System.out.println(thread.getState());//线程销毁后的状态
}
}
Multi-threaded concurrent execution improves the code execution rate, but it also causes some security issues for the following reasons:
1. Random scheduling/preemptive execution of the operating system [There is nothing we can do about this method]
2. Multiple threads modify the same variable
Solution: Destroy the above conditions by adjusting the design of the program
3. Some modification operations TM are not atomic
Solution: Through the shackle operation, you can package some non-atomic operations into an atomic operation
4. Memory visibility
5. Instruction reordering
Problems 4 and 5 are all solved through the volatile keyword.