Java使用Thread時的一些注意點

2021-08-21 16:03:01 字數 1949 閱讀 5059

新建執行緒很簡單,只要使用new關鍵字建立乙個執行緒物件,並且將它start()起來即可:

thread t1 = new thread();

t1.start();

注意:下面的**也能通過編譯和正常執行,但是卻沒有新建乙個執行緒:

thread t2 = new thread();

t2.run();

這只是簡單的普通方法呼叫,所以沒有涉及新的執行緒建立。

那讓我們來看看thread的run方法裡面是什麼:

@override

public void run()

}

這個target是什麼呢:

/* what will be run. */

private runnable target;

原來target就是乙個runnable,而這個runnable是什麼時候進行賦值的呢:

public thread(runnable target)
這是其中乙個建構函式,可以看到當你在新建乙個thread時候,傳入的runnable傳入init方法,在init內部可以看到這個runnable是賦值給了上面所說的target,再來看回thread的run方法:

@override

public void run()

}

所以其實邏輯很簡單,就是看你有沒有傳入乙個runnable,如果有就執行你傳入的runnable的run方法。

下面進行測試:

public static void main(string args) 

})};

t1.start();

}

測試結果:

自己去試試吧!

嚴格來說,執行緒中斷並不會使執行緒立即退出,而是給執行緒傳送乙個通知,告知目標執行緒,至於目標執行緒接到通知後如何處理,則完成由目標執行緒自行決定。

public void thread.interrupt()               //中斷執行緒

public boolean thread.isinterrupted() //判斷是否被中斷

public static boolean thread.interrupted() //判斷是否被中斷,並清除當前中斷狀態

測試:

public static void main(string args) throws interruptedexception 

}});

t.start();

t.interrupt();

}

這裡雖然對執行緒t進行中斷,但是t並沒有中斷處理的邏輯,因此就算t執行緒被置上了中斷狀態,這個中斷也不會有任何作用。

如果希望執行緒t在中斷後退出,就必須為它增加相應的處理**:

public static void main(string args) throws interruptedexception 

thread.yield();}}

});t.start();

t.interrupt();

}

這樣就能達到響應中斷的方法。

注意點:

thread.sleep由於中斷丟擲異常,但是會清除中斷標記:

public static void main(string args) throws interruptedexception  catch (interruptedexception e) 

}});

t.start();

t.interrupt();

}

執行結果:

自己試試吧!

Java併發程式設計 Thread類的使用 1

專案環境 專案中有乙個1分鐘輪詢的job,每次輪詢會啟動乙個執行緒 thread 但是會出現1分鐘內,這個執行緒的工作不能處理完畢,下乙個輪詢的執行緒就進來了,會造成資料多次處理。這不是我想要的 在這種環境下,考慮到需要使用synchronized 同步鎖 確保資料的的唯一性和準確性。定時處理批任務...

再談Java的Thread機制 3

同步出現的原因是當執行緒中使用共享資源時候,為了資源的獨占性。這樣可以避免獲得結果是不正確的。如果,不是使用共享資源,不建議使用同步!因為這會使多執行緒變成單執行緒!而且處理不當,會引起死鎖!比如我們所寫執行緒程式要的結果是 count value is 1 count value is 2 cou...

再談Java的Thread機制 3

同步出現的原因是當執行緒中使用共享資源時候,為了資源的獨占性。這樣可以避免獲得結果是不正確的。如果,不是使用共享資源,不建議使用同步!因為這會使多執行緒變成單執行緒!而且處理不當,會引起死鎖!比如我們所寫執行緒程式要的結果是 count value is 1 count value is 2 cou...