1、線程禮讓
(1)禮讓線程,讓當前正在執行的線程暫停,但不阻塞
(2)將線程從運行狀態轉為就緒狀態
(3)讓cpu重新調度,禮讓不一定成功!看cpu心情
package state;
?
//測試禮讓線程
//禮讓不一定成功,看cpu心情
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{
?@Overridepublic void run() {System.out.println(Thread.currentThread().getName()+"線程開始執行");Thread.yield();//禮讓System.out.println(Thread.currentThread().getName()+"線程停止執行");}
}
線程禮讓成功

線程禮讓失敗

2、線程強制執行
package state;
?
//測試Join方法 想象為插隊
public class TestJoin implements Runnable{@Overridepublic void run() {for (int i = 0; i < 1000; i++) {System.out.println("線程VIP來了"+i);}}
?public static void main(String[] args) {TestJoin testJoin = new TestJoin();new Thread(testJoin).start();
?//主線程for (int i = 0; i < 1000; i++) {if (i==200){try {new Thread(testJoin).join();} catch (InterruptedException e) {throw new RuntimeException(e);}}System.out.println("主線程"+i);}}
}
3、線程狀態觀測
package state;
?
//觀察測試線程的狀態
public class TestState {public static void main(String[] args) {//lambda表達式Thread thread = new Thread(()->{for (int i = 0; i < 5; i++) {try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}}System.out.println("///");});
?//觀察狀態Thread.State state = thread.getState();System.out.println(state);//New//觀察啟動后thread.start();//啟動線程state = thread.getState();System.out.println(state);
?while (state!=Thread.State.TERMINATED){//只要線程不終止,就一直輸出狀態try {Thread.sleep(100);state = thread.getState();//更新線程狀態System.out.println(state);//輸出狀態} catch (InterruptedException e) {throw new RuntimeException(e);}}}
}