“This is the sixth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
Five states of threads
Create, ready, Run, block, die
Once created, the Thread new Thread() enters the new state
When the start method is called, the thread immediately enters the ready state, but it does not immediately schedule execution. The running thread is actually executing the code block in the thread body
When sleep, wait, or thread lock is called, the thread enters a blocking state, meaning that the code does not execute until the lock is released and the code enters the ready state and waits for the CPU to schedule execution
A thread interrupts or terminates and does not start again once it is dead
Stop the thread
-
The stop(), destory() methods provided by the JDK are not recommended
-
It is recommended that threads stop themselves
-
It is recommended that a flag bit be used to terminate the variable, terminating the thread when flag = false
Implement a stop-thread demo
Public class TestStop implements Runnable {// Set a flag bit private Boolean flag = true; @Override public void run() { int i = 0; while (flag) { System.out.println("Thread run..." + i++); }} public void stop() {this.flag = false; } public static void main(String[] args) { TestStop testStop = new TestStop(); new Thread(testStop).start(); for (int i = 0; i < 1000; I ++) {system.out.println (" mainline "+ I); If (I == 999) {// call stop to switch flag teststop.stop (); System.out.println(" Thread should stop "); }}}}Copy the code
The results
Thread to sleep
Sleep (time) specifies the number of milliseconds in which the current thread is blocked
The thread enters the ready state when the time for sleep() is reached
Sleep () method throws Java. Lang. InterruptedException, when used for processing
Every object has a lock, and sleep does not release the lock
A previous thread creation article juejin.cn/post/702674… The ticket-snatching demo uses thread sleep to simulate network latency
The difference between sleep() and wait()
-
Locks are released differently: sleep() does not release locks while holding them
-
The scope varies: Wait must be used in synchronized code blocks, and sleep can be used anywhere
-
Whether to catch exceptions or not: Sleep needs to catch exceptions, wait does not
-
Different classes Object –> Wait Thread –> sleep