標籤:size 子線程 tde ace lang imp 斷線 cep 放棄
1.interrupt()方法
interrupt方法不會真正中斷線程,它只會清楚線程的wait,sleep,join的受阻狀態,時線程重新獲得CPU的執行權。
此時如果再次調用線程的wait,sleep,join方法,將會拋出一個InterruptedException異常
package threadinterrupt;public class InterruptDemo {public static void main(String[] args) throws InterruptedException {Thread t = new Thread(new Runnable() {private boolean flag = true;@Overridepublic void run() {synchronized (this) {int i = 1;while(flag){System.out.println("=========" + i++ + "=========");if (i > 10) {try {System.out.println("子線程將停止執行");i =0;wait();} catch (InterruptedException e) {System.out.println("第二次調用wait()時拋出異常");e.printStackTrace();break;}}}}}});t.start();Thread.sleep(2000);t.interrupt();System.out.println("子線程將繼續執行");}}
2.join()方法,t1.join方法代表著當前線程放棄CPU執行資格,需要等到t1執行完畢時才能獲得CPU執行資格
package threadinterrupt;import java.lang.Thread.State;public class ThreadJoin {public static void main(String[] args) throws InterruptedException {Runnable r = new Runnable() {@Overridepublic void run() {for (int i = 0; i < 1000; i++) {System.out.println(Thread.currentThread().getName()+":========"+i+"========");}}};Thread t1 = new Thread(r);Thread t2 = new Thread(r);t1.start();t2.start();//System.out.println("主線程需要等到t1執行完畢才會執行");//t1.join();if(t1.getState() == State.RUNNABLE){System.out.println("【沒有】t1.join()時這句話會被執行");}if(t1.getState() == State.TERMINATED){System.out.println("【有】t1.join()時這句話會被執行");}}}
3.yield()方法,暫停當前正在執行的線程對象,並執行其他線程,該方法不會讓該線程放棄CPU的執行權,該線程任然可以爭奪CPU執行權
package threadinterrupt;public class ThreadYield {public static void main(String[] args) {Runnable r = new Runnable() {@Overridepublic void run() {for (int i = 0; i < 1000; i++) {System.out.println(Thread.currentThread().getName()+ ":========" + i + "========");Thread.yield();}}};Thread t1 = new Thread(r);Thread t2 = new Thread(r);System.out.println("在子線程的run方法中添加Thread.yield();兩個線程將會交替(不是絕對交替)");t1.start();t2.start();}}
4.setDaemon(boolean on)方法,將該線程標記為守護線程或使用者線程。
5.setPriority(int newPriority) 更改線程的優先順序(1-10)數字越大,優先順序越高
Java多線程其他