標籤:this yield read static resume rup 技術 i+1 todo
1、異常法
public class MyThread extends Thread { @Override public void run() { super.run(); try { for (int i = 0; i < 5000000; i++) { if(this.interrupted()){ System.out.println("我要停止了。。。。。"); throw new InterruptedException(); \\拋出異常 } System.out.println("i="+(i+1)); } System.out.println("我在for下邊。。"); } catch (InterruptedException e) { System.out.println(" in MyThread catch.."); e.printStackTrace(); } } public static void main(String[] args) { try { MyThread myThread=new MyThread(); myThread.start(); Thread.sleep(2000); myThread.interrupt(); } catch (InterruptedException e) { System.out.println("main catch"); e.printStackTrace(); } System.out.println("end"); }}
結果:
2,在沉睡中停止,即在sleep()狀態下停止。
public class MyThread extends Thread { @Override public void run() { super.run(); try { System.out.println("run begin"); Thread.sleep(200000); System.out.println("run end"); } catch (InterruptedException e) { System.out.println("在沉睡中被停止!進入catch!"+this.isInterrupted()); e.printStackTrace(); } } public static void main(String[] args) { try { MyThread thread = new MyThread(); thread.start(); Thread.sleep(200); thread.interrupt(); } catch (InterruptedException e) { System.out.println("main catch"); e.printStackTrace(); } System.out.println("end!"); }}
結果:
3、暴力停止 stop()(已作廢方法,不推薦使用)
注意:
(1)、暴力停止,可能導致清理工作完成不了。
(2)、導致資料的不到同步處理,導致資料不一致問題。
public class MyThread extends Thread { private int i = 0; @Override public void run() { try { while (true) { i++; System.out.println("i=" + i); Thread.sleep(1000); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { try { MyThread thread = new MyThread(); thread.start(); Thread.sleep(8000); thread.stop(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
4、使用ruturn停止線程
public class MyThread extends Thread { @Override public void run() { while (true) { if (this.isInterrupted()) { System.out.println("停止了!"); return; } System.out.println("timer=" + System.currentTimeMillis()); } } public static void main(String[] args) throws InterruptedException { MyThread t=new MyThread(); t.start(); Thread.sleep(2000); t.interrupt(); }}
結果:
二、
(1)suspend 與 resume 的優缺點:
缺點:(1)獨佔——使用不當,極易造成公用的同步對象的獨佔,是其他線程無法訪問公用的同步對象。
(2) 不同步——因為線程的暫停而導致資料不同步的情況。
(2)、yield() 方法 :放棄當前CPU資源,讓其他的任務去佔用CPU資源。放棄時間不確定,可能剛剛放棄,馬上又獲得了CPU時間片。
二、java多線程編程核心技術之(筆記)——如何停止線程?