一般來說,主方法main()結束的時候線程結束


suspend()是將一個運行時狀態進入阻塞狀態(注意不釋放鎖標記)。恢復狀態的時候用resume()。Stop()指釋放全部。

這幾個方法上都有Deprecated標志,說明這個方法不推薦使用。

 

一般來說,主方法main()結束的時候線程結束,可是也可能出現需要中斷線程的情況。對於多線程一般每個線程都是一個循環,如果中斷線程我們必須想辦法使其退出。

 

如果主方法main()想結束阻塞中的線程(比如sleep或wait)

那么我們可以從其他進程對線程對象調用interrupt()。用於對阻塞(或鎖池)會拋出例外Interrupted Exception。

這個例外會使線程中斷並執行catch中代碼。

 

多線程中的重點:實現多線程的兩種方式,Synchronized,以及生產者和消費者問題(ProducerConsumer.java文件)。

 

 1 package TomTexts;
 2 
 3 import java.util.*;
 4     class Counter { 
 5           int i = 1; 
 6           public String toString() { 
 7                 return Integer.toString(i); 
 8           }
 9         }
10         class TomTexts_23 {
11           public static void main(String[] args) {
12                 Hashtable ht = new Hashtable();
13                 for(int i = 0; i < 10000; i++) {
14                       // Produce a number between 0 and 20:
15                       Integer r = new Integer((int)(Math.random() * 20));
16                   if(ht.containsKey(r))
17                         ((Counter)ht.get(r)).i++;
18                   else
19                         ht.put(r, new Counter());
20                 }
21                 System.out.println(ht);
22           }
23         } 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM