Thread status
Threads are considered lightweight processes in the operating system, so the thread state of the operating system is consistent with the process state of the operating system
1. Five thread states
-
Create a state of
Thread t = new Thread() The Thread object enters the new state once it is created
-
The ready state
When the start() method is called, the thread enters the ready state, but it does not execute immediately
-
Running state
When running, the thread will actually execute the code in the thread body
-
The blocking state
When sleep(), wait(), or synchronous locking is called, the thread is blocked and the code does not continue. Wait for the blocking event to be cleared, and then re-enter the ready state, waiting for the CPU scheduling to execute
-
State of death
A thread interrupts or terminates and cannot be started again once it is dead
2. Some methods in threads
setPriority(int newPriority)
Changes the priority of a threadstatic void sleep(long millis)
Hibernates the currently executing thread for the specified number of millisecondsvoid join()
Merge a thread and wait for it to terminate before executing another threadstatic void yield()
Suspends the currently executing thread and executes another threadvoid interrupt()
Interrupt thread (try not to use it)boolean isAlive()
Tests whether the thread is active
Second, manipulating threads
1. Stop the thread
1.1 points
- Using the JDK provided is not recommended
stop()
,destory()
Methods such as - It is recommended to wait for the thread to stop itself, for example using
for
Limit the number of cycles and do not recommend dead cycles - It is recommended to terminate a variable with a flag bit, such as when
flag == false
When the thread is terminated
1.2 the sample
public class TestStop implements Runnable {
// 1. Define the identity
private static boolean flag = true;
@Override
public void run(a) {
int i = 0;
while (flag) {
System.out.println("run...... Thread " + i++);
if (i >= 30) {
TestStop.stop();
System.out.println("This thread has stopped"); }}}// 2. Change the identifier of the external provision method
public static void stop(a) {
flag = false;
}
public static void main(String[] args) {
TestStop t = new TestStop();
new Thread(t).start();
for (int i = 0; i < 100; i++) {
System.out.println("The main thread"+ i); }}}Copy the code
2. Thread spin-down
2.1 points
sleep()
Specifies the number of milliseconds in which the current thread is blockedsleep()
Method is abnormal.InterruptedException
sleep()
The thread enters the ready state when the time reachessleep()
Can simulate network delay, countdown and so on- Every object has a lock,
sleep()
Lock not released
2.2 the sample
case1.Simulate network latency to amplify the probability of possible problemspublic class TestSleep implements Runnable {
private int ticketNum = 10;
@Override
public void run(a) {
while (true) {
if (ticketNum <= 0) {
break;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "Got the number one." + ticketNum-- + "Ticket"); }}public static void main(String[] args) {
TestSleep t = new TestSleep();
new Thread(t, "Xiao Ming").start();
new Thread(t, "Teacher").start();
new Thread(t, "Scalpers").start(); }} case2.Analog countdownpublic class TestSleep {
public static void tenDown(a) throws InterruptedException {
int num = 10;
while (true) {
Thread.sleep(1000);
System.out.println(num--);
if (num <= 0) {
break; }}}public static void main(String[] args) {
try {
tenDown();
} catch(InterruptedException e) { e.printStackTrace(); }}}Copy the code
3. Thread comity
3.1 points
- Yield to the thread and suspend the currently executing thread
- Moves a thread from the running state to the ready state
- Let the CPU rescheduling, conciliation success depends on CPU scheduling
3.2 the sample
public class TestYield {
public static void main(String[] args) {
MyYield m = new MyYield();
new Thread(m, "a").start();
new Thread(m, "b").start(); }}class MyYield implements Runnable {
@Override
public void run(a) {
System.out.println(Thread.currentThread().getName() + "Thread starts executing");
Thread.yield();
System.out.println(Thread.currentThread().getName() + "Thread stopped executing"); }}Copy the code
4. Thread execution is mandatory
4.1 points
join
Merge thread, wait for this thread to finish execution, then execute other threads. Other threads block during that time- Similar to queue-jumping in real life
4.2 the sample
public class TestJoin implements Runnable {
@Override
public void run(a) {
for (int i = 0; i < 200; i++) {
System.out.println("Line jumpers"+ i); }}public static void main(String[] args) throws InterruptedException {
TestJoin t = new TestJoin();
Thread thread = new Thread(t);
thread.start();
for (int i = 0; i < 100; i++) {
if (i == 50) {
thread.join();
}
System.out.println("Main method thread"+ i); }}}Copy the code
Observe thread status
public class TestState {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("/ / / / / / / / / /");
});
Thread.State state = t.getState();
System.out.println(state);
// Check the startup status
t.start();
state = t.getState();
System.out.println(state);
// Repeat monitoring during thread execution
while(state ! = Thread.State.TERMINATED) { Thread.sleep(100); state = t.getState(); System.out.println(state); }}}Copy the code
Four, extension,
Six states of Java threads
NEW
: The creation is not started, indicating that the creation is not invokedstart()
methodsRUNNABLE
: Runnable. A thread in this state may be running in a Java VIRTUAL machine, or may be waiting for CPU allocation, which includes traditional operating system thread statesready
andrunnig
Two statesBLOCKED
: blocked. The thread in this state is waiting for the lock to be released to enter the synchronization zoneWAITING
: Wait. A thread in this state needs to be woken up by another thread before it can be convertedRUNNABLE
stateTIMED_WATING
: Time waiting, waiting for a specified time will be woken upTERMINATED
: Terminates. The thread has finished executing