Java多線程常見面試問題及解答

學識都 人氣:2.54W

問題:進程和線程的區別

Java多線程常見面試問題及解答

解答:一個進程對應一個程序的執行,而一個線程則是進程執行過程中的一個單獨的執行序列,一個進程可以包含多個線程。線程有時候也被稱為輕量級進程.

一個Java虛擬機的實例運行在一個單獨的進程中,不同的線程共享Java虛擬機進程所屬的堆內存。這也是為什麼不同的線程可以訪問同一個對象。線 程彼此共享堆內存並保有他們自己獨自的棧空間。這也是為什麼當一個線程調用一個方法時,他的局部變量可以保證線程安全。但堆內存並不是線程安全的,必須通 過顯示的聲明同步來確保線程安全。

問題:列舉幾種不同的創建線程的方法.

解答:可以通過如下幾種方式:

•  繼承Thread 類

•  實現Runnable 接口

•  使用Executor framework (這會創建一個線程池)

123456789101112131415class Counter extends Thread {     //method where the thread execution will start     public void run(){        //logic to execute in a thread        }     //let’s see how to start the threads    public static void main(String[] args){       Thread t1 = new Counter();       Thread t2 = new Counter();       t1.start();  //start the first thread. This calls the run() method.       t2.start(); //this starts the 2nd thread. This calls the run() method.      }}
123456789101112131415class Counter extends Base implements Runnable{     //method where the thread execution will start     public void run(){        //logic to execute in a thread        }     //let us see how to start the threads    public static void main(String[] args){         Thread t1 = new Thread(new Counter());         Thread t2 = new Thread(new Counter());         t1.start();  //start the first thread. This calls the run() method.         t2.start();  //this starts the 2nd thread. This calls the run() method.      }}

通過線程池來創建更有效率。

問題:推薦通過哪種方式創建線程,為什麼?

解答:最好使用Runnable接口,這樣你的類就不必繼承Thread類,不然當你需要多重繼承的時候,你將 一籌莫展(我們都知道Java中的類只能繼承自一個類,但可以同時實現多個接口)。在上面的例子中,因為我們要繼承Base類,所以實現Runnable 接口成了顯而易見的選擇。同時你也要注意到在不同的例子中,線程是如何啟動的。按照面向對象的方法論,你應該只在希望改變父類的行為的時候才去繼承他。通 過實現Runnable接口來代替繼承Thread類可以告訴使用者Counter是Base類型的一個對象,並會作為線程執行。

問題:簡要的`説明一下高級線程狀態.

解答:下圖説明了線程的各種狀態.

• 可執行(Runnable):當調用start()方法後,一個線程變為可執行狀態,但是並不意味着他會立刻開始真正地執行。而是被放入線程池,