Thread state of Java
Thread method
method | explain |
---|---|
setPriority(int newPriority) | Change the priority of a thread |
static void sleep(long millis) | Hibernates the currently executing thread for the specified number of milliseconds |
void join() | Wait for the thread to terminate |
static void yield() | Pauses the currently executing thread object and executes other threads |
void interrupt() | Interrupt the thread. Don't do it this way |
boolean isAlive() | Test whether the thread is active |
Stop thread
- The stop() and destroy() methods provided by JDK are not recommended. [abandoned]
- It is recommended that the thread stop by itself
- It is recommended to use a flag bit to terminate the variable. When flag=false, the thread will be terminated.
package com.cnblogs.thread; /* Test stop */ public class TestStop implements Runnable{ //Set flag bit private boolean flag = true; @Override public void run() { int i = 0; while(flag){ System.out.println("run...." + i++); } } //Set an open method to stop the thread and convert the flag bit 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("main" + i); if(i == 520){ testStop.stop(); System.out.println("The thread stopped"); } } } }
Thread sleep
- Sleep specifies the number of milliseconds the current thread is blocking
- Exception InterruptedException exists in sleep;
- When the sleep time reaches, the thread enters the ready state
- sleep can simulate network delay, countdown, etc.
- Each object has a lock, and sleep does not release the lock
package com.cnblogs.thread; import java.util.Date; /* Analog countdown */ public class TestSleep { public static void tenDown() throws InterruptedException { int num = 10; while(true){ Thread.sleep(1000); System.out.println(num--); if(num <= 0){ break; } } } public static void main(String[] args) { Date startTime = new Date(System.currentTimeMillis());//get SysTime try { tenDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }
package com.cnblogs.thread; import java.text.SimpleDateFormat; import java.util.Date; /* Print time */ public class TestSleep { public static void tenDown() throws InterruptedException { int num = 10; while(true){ Thread.sleep(1000); System.out.println(num--); if(num <= 0){ break; } } } public static void main(String[] args) { Date startTime = new Date(System.currentTimeMillis());//get SysTime while(true){ try { Thread.sleep(1000); System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime)); startTime = new Date(System.currentTimeMillis());//Update current time } catch (InterruptedException e) { e.printStackTrace(); } } } }
Thread comity
- Comity thread, which suspends the currently executing thread without blocking
- Transition a thread from a running state to a ready state
- Note: if the CPU rewrites the schedule, comity may not be successful! Look at CPU mood
package com.cnblogs.thread; /* Test comity thread */ public class TestYield { public static void main(String[] args) { MyYield myYield = new MyYield(); new Thread(myYield,"a").start(); new Thread(myYield,"b").start(); } } class MyYield implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName() + "Thread starts execution"); Thread.yield();//Comity System.out.println(Thread.currentThread().getName() + "Thread end execution"); } } /* Effect before comity: a Thread starts execution a Thread end execution b Thread starts execution b Thread end execution Results after comity: a Thread starts execution b Thread starts execution a Thread end execution b Thread end execution */
Thread enforcement
- Join merge threads. After this thread completes execution, execute other threads. Other threads are blocked
- Imagine jumping in line
package com.cnblogs.thread; public class TestJoin implements Runnable{ @Override public void run() { for (int i = 0; i < 50; i++) { System.out.println("VIP Here comes the thread!!!" + i); } } public static void main(String[] args) throws InterruptedException { //Start thread TestJoin testJoin = new TestJoin(); Thread thread = new Thread(testJoin); thread.start(); for (int i = 0; i < 1000; i++) { if(i >= 200){ thread.join(); } System.out.println("main Thread!!!" + i); } } }
Thread state observation
Thread.State
A thread can be in one of the following states:
-
New
- Threads that have not been started are in this state
-
RUNNABLE
- The thread executing in the Java virtual machine is in this state
-
BLOCKED
- Threads that are blocked waiting for a monitor lock are in this state
-
WAITING
- A thread that is waiting for another thread to perform a specific action is in this state
-
TIMED_WAITING
- The thread that is waiting for another thread to perform the action for the specified waiting time is in this state
-
TERMINATED
- The exited thread is in this state
A thread can be in a state at a given point in time. These states are virtual machine states that do not reflect the state of any operating system threads.
package com.cnblogs.thread; public class TestState { public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(()->{ for (int i = 0; i < 5; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("0.0"); }); //Observation state Thread.State state = thread.getState(); System.out.println(state);//NEW //After observation start thread.start(); state = thread.getState(); System.out.println(state);//RUNNABLE //monitor while (state != Thread.State.TERMINATED){ Thread.sleep(100); state = thread.getState(); System.out.println(state);//This time_ WAITING } //TERMINATED after the thread ends } }
thread priority
-
Java provides a thread scheduler to monitor all threads that enter the ready state after startup. The thread scheduler determines which thread should be scheduled to execute according to priority.
-
The priority of threads is expressed in numbers, ranging from 1 to 10
- Thread.MIN_PRIORITY = 1;
- Thread.MAX_PRIORITY = 10;
- Thread.NORM_PRIORITY = 5;
-
Change or get priority in the following ways
- getPriority.setPriority(int xxx);
package com.cnblogs.thread; public class TestPriority{ public static void main(String[] args) { //Default priority of main thread System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority()); MyPriority myPriority = new MyPriority(); Thread t1 = new Thread(myPriority); Thread t2 = new Thread(myPriority); Thread t3 = new Thread(myPriority); Thread t4 = new Thread(myPriority); //The default is 5 t1.start(); t2.setPriority(7); t2.start(); t3.setPriority(Thread.MAX_PRIORITY); t3.start(); t4.setPriority(Thread.MIN_PRIORITY); t4.start(); /* main-->5 Thread-2-->10 Thread-1-->7 Thread-0-->5 Thread-3-->1 */ } } class MyPriority implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority()); } }
Daemon thread
- Threads are divided into user threads and daemon threads
- The virtual machine must ensure that the user thread has completed execution
- The virtual machine does not have to wait for the daemon thread to finish executing
- For example, record operation logs in the background, monitor memory, garbage collection, etc
package com.cnblogs.thread; /* Test daemon thread */ public class TestDeamon { public static void main(String[] args) { God god = new God(); You1 you1 = new You1(); Thread thread = new Thread(god); thread.setDaemon(true); thread.start();//God thread start new Thread(you1).start(); } } //lord class God implements Runnable{ @Override public void run() { while(true){ System.out.println("God is watching over you..."); } } } //you class You1 implements Runnable{ @Override public void run() { for (int i = 0; i < 36500; i++) { System.out.println("You live happily every day!!!"); } System.out.println("Goodbye, world"); } }
Tag: [thread]