I. Thread Status and Stop Threads of S02E174_01
Thread state
New state: When a thread object is created with a new keyword and a Thread class or subclass, the thread object is in a new state. Threads in a new state have their own memory space and can enter the ready state (Runnable) by calling the start method
Ready state: Threads in ready state already have running conditions, but have not yet been allocated to the CPU, in the thread ready queue, waiting for the system to allocate CPU for them. Waiting state is not the state of execution. When a Thread object is selected, it will enter the state of execution from the state of waiting execution. The action selected by the system is called "CPU scheduling". Once the CPU is obtained, the thread enters the running state and automatically calls its own run method.
Running state: Threads in running state execute code in their own run methods until they call other methods and terminate, or wait for a resource to block or complete a task and die. If the execution is not finished within a given time slice, it will be replaced by the system and returned to the waiting execution state. -
Blocking state: In some cases, threads in running state, such as executing sleep (sleep) methods, or waiting for resources such as I/O devices, will give up the CPU and temporarily stop their operation, and enter blocking state. Threads in blocked state can not enter ready state. Only when the cause of blocking is eliminated, such as sleep time has arrived or waiting I/O devices are idle, threads will turn to ready state and queue up in ready queue again. After being selected by the system, they will continue to run from the original stop position.
Dead state: Dead state is the last stage in the thread life cycle. There are two causes of thread death. One is that a running thread completes all of its work; the other is that the thread is forced to terminate, such as by executing stop or destroy methods (neither method is recommended). The former produces exceptions, while the latter terminates compulsively and does not release locks. (b)
Stop threads
1. Natural termination: the normal execution of the thread body is complete
2. External interference:
Define the identity used by the thread body in the thread class
Thread body uses this identifier
Provide external methods to change the logo
This method can be called externally according to conditions.
package com.test.thread.status; public class TestStatus { public static void main(String[] args) { Study s = new Study(); new Thread(s).start(); //External interference for (int i = 0; i < 100000; i++) { if(50000 == i){//External interference s.stop(); System.out.println("stop...-->>" + i); } } } } class Study implements Runnable{ //Define the identity used by the thread body in the thread class private boolean flag = true; @Override public void run() { //Thread bodies use this identifier while(flag){ System.out.println("study thread..."); } } //External Provision Method Change Identification public void stop(){ this.flag = false; } }
- 2. S02E175_01 Thread Blocking 1_join_yield
3. S02E176_01 Thread Blocking 2_sleep_Countdown_Network Delay
1. join: merge threads
2. yield: pause your own thread (the static method, pause for a while, and may be called again in the next millisecond, depending on the CPU)
3. sleep: sleep, do not release locks
1) Time-related: Countdown
2) Analog Network Delay
package com.test.thread.status; /** * join: Merge threads */ public class TestJoin extends Thread { public static void main(String[] args) throws InterruptedException { TestJoin testJoin = new TestJoin(); Thread t = new Thread(testJoin);//New State t.start();//Readiness //CPU Scheduling Operation for (int i = 0; i < 1000; i++) { if(50==i){ t.join();//main blocking, waiting for t to finish } System.out.println("main..."+i); } } @Override public void run() { for (int i = 0; i < 1000; i++) { System.out.println("join..."+i); } } }
package com.test.thread.status; /** * yield: Pause your own thread (static method, pause for a while, and may be called again in the next millisecond, depending on the CPU) */ public class TestYield extends Thread { public static void main(String[] args) { TestYield testYield = new TestYield(); Thread t = new Thread(testYield); t.start(); for (int i = 0; i < 1000; i++) { if(0==i%200){ //Pause the current thread Thread.yield();//Pause for a moment, and it may be called again in the next millisecond, depending on the CPU. } System.out.println("main..."+i); } } @Override public void run() { for (int i = 0; i < 1000; i++) { System.out.println("yield..."+i); } } }
package com.test.thread.status; import java.text.SimpleDateFormat; import java.util.Date; /** * Count down * 1,Count down 10 numbers, print one in a second * 2,Count down */ public class TestSleep { public static void main(String[] args) throws InterruptedException { test1(); test2(); } /** * 1,Count down 10 numbers, print one in a second * @throws InterruptedException */ public static void test1() throws InterruptedException{ int num = 10; while(true){ System.out.println(num--); Thread.sleep(1000);//suspend if(num <= 0){ break; } } } /** * 2,Count down * @throws InterruptedException */ public static void test2() throws InterruptedException{ Date endTime = new Date(System.currentTimeMillis() + 10*1000); long end = endTime.getTime(); while(true){ //output System.out.println(new SimpleDateFormat("mm:ss").format(endTime)); //Wait a second Thread.sleep(1000); //Build the next second time endTime = new Date(endTime.getTime() - 1000); //Continue within 10 seconds or quit if(end-10000 > endTime.getTime()){ break; } } } }
package com.test.thread.status; /** * sleep Analog network delay * Causing concurrency problems ... Passer-by armour grabbed 44 The siege lion grabbed 44 ... Passer-by armour grabbed 1 The siege lion grabbed 0 Cattle B snatched - 1 */ public class TestSleep2 { public static void main(String[] args) { //Real roles Web12306 web = new Web12306(); //agent Thread t1 = new Thread(web, "Passerby A"); Thread t2 = new Thread(web, "Cattle B"); Thread t3 = new Thread(web, "Siege Lion"); t1.start(); t2.start(); t3.start(); } } class Web12306 implements Runnable { private int num = 50;//Numbers 1 to 50 @Override public void run(){ while(true) { if(num <= 0){ break;//Break } try { Thread.sleep(500);//t1, t2, t3 may all be waiting, num may be the same or - 1 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "I got it." + num--); } } }
4. S02E177_01 Thread Basic Information _Priority
package com.test.thread.info; public class MyThread implements Runnable { private boolean flag = true; private int num = 0; @Override public void run() { while(flag){ System.out.println(Thread.currentThread().getName()+ "-->>" + num++); } } public void stop(){ flag = !flag; } }
package com.test.thread.info; /** * Thread.currentThread * setName() * getName() * isAlive */ public class InfoDemo { public static void main(String[] args) throws InterruptedException { MyThread it = new MyThread(); Thread proxy = new Thread(it,"To be kicked"); proxy.setName("test"); System.out.println(proxy.getName()); System.out.println(Thread.currentThread().getName());//main proxy.start(); System.out.println("Post-startup status:" + proxy.isAlive()); Thread.sleep(50); it.stop(); Thread.sleep(100);//After stop, the CPU does not necessarily stop immediately. Sleep to see the effect. System.out.println("The state after stopping:" + proxy.isAlive()); } }
package com.test.thread.info; /** * Priority: Probability, not absolute order * MAX_PRIORITY 10 * NORM_PRIORITY 5(Default) * MIN_PRIORITY 0 * * setPriority() * getPriority() */ public class InfoPriority { public static void main(String[] args) throws InterruptedException { MyThread it1 = new MyThread(); Thread p1 = new Thread(it1,"Kicked 1"); MyThread it2 = new MyThread(); Thread p2 = new Thread(it2,"Kicked 2"); p1.setPriority(Thread.MIN_PRIORITY); p2.setPriority(Thread.MAX_PRIORITY); p1.start(); p2.start(); Thread.sleep(100); it1.stop(); it2.stop(); } }