Java 停止線程

來源:互聯網
上載者:User

最近老是碰到線程不能停掉的問題,為解決此問題苦了一小天,最後參看別人資料得以解決,先總結如下

1,最常用的方法通過一個布爾類型變數控制

例如:

class TestThread implements Runnable{boolean flag=true;@Overridepublic void run() {while(flag){doSomething();try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}void doSomething(){}}

但是當程式二次啟動時,這個線程還會繼續,因為線程沒有進入Run的狀態,線程並沒有真的停掉,所以這種方法並不好

當線程sleep()或者wait()時通過調用interrupt()方法使其發生InterruptedException異常來退出線程。


2,如果程式因為I/O而停滯,進入Not Runnable狀態時,無法使用interrupt()方法使其發生InterruptedException異常來退出線程,這個例外要如何引發,要看您所使用的I/O而定,

例如您使用readLine()在等待網路上的一個資訊,此時線程進入Not
Runnable直到讀到一個資訊,您要讓它離開run()的方法就是使用close()關閉它的串流,

這時會引發一個IOException例外而使得線程離開run()方法


3,如果是網路接收資料而引起的,則需要關閉socket,使得線程離開run()方法

例如:

private DatagramSocket ds=null;private class UDPThread implements Runnable{byte[] buf=new byte[1024];@Overridepublic void run() {while(ds!=null){DatagramPacket dp=new DatagramPacket(buf, buf.length);try {ds.receive(dp);parse(dp);Log.e("tag", "receive a package from server");} catch (IOException e) {e.printStackTrace();}}}

以上這個例子必須執行ds.close()方法線程才可停止,要不然線程會一直存在。

4,線程停止還可以調用join()方法去阻塞線程,可適用以上幾種情況,好了先介紹到這裡,有問題可留言。




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.