Java多線程中的兩個問題

來源:互聯網
上載者:User
多線程|問題 多線程中Thread.stop()被廢棄的原因:
當調用Thread.stop()方法時,該線程將釋放先前其控制的所有資源,而線上程沒有正常執行完畢之前強迫Stop之後,這些資源可能處在一種不一致的狀態,而這些處於不一致的狀態的資源被其他的線程所使用之後,就可能會發生一些意想不到的錯誤。
實現時間差事件的解決辦法:
在主線程中設定一個狀態變數,在響應線程執行時,先sleep()一個固定的時間段,之後檢查主線程的這個狀態,如果這個狀態不同就執行不同的操作,或停止執行。
可以通過回調機制來實現響應線程對主線程變數的查看,例如:
Test.java
public class Test {
private volatile ThreadTest test;
public boolean flag = true;
public Test() {
test = new ThreadTest(this);
}
public static void main(String[] args){
Test test = new Test();
test.test.start();
test.flag = false;
test = null;
}
}
ThreadTest.java
public class ThreadTest extends Thread{
Test test;
public ThreadTest(Test test) {
this.test = test;
}
public void run() {
try{
sleep(1000);
if (test.flag)
System.out.println("I've waken up!");
}catch(Exception e){
e.printStackTrace();
}
}
}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.