Java多線程常見面試問題及解答
問題:進(jìn)程和線程的區(qū)別
解答:一個(gè)進(jìn)程對(duì)應(yīng)一個(gè)程序的執(zhí)行,而一個(gè)線程則是進(jìn)程執(zhí)行過(guò)程中的一個(gè)單獨(dú)的執(zhí)行序列,一個(gè)進(jìn)程可以包含多個(gè)線程,
Java多線程常見面試問題及解答
。線程有時(shí)候也被稱為輕量級(jí)進(jìn)程.一個(gè)Java虛擬機(jī)的實(shí)例運(yùn)行在一個(gè)單獨(dú)的進(jìn)程中,不同的線程共享Java虛擬機(jī)進(jìn)程所屬的堆內(nèi)存。這也是為什么不同的線程可以訪問同一個(gè)對(duì)象。線 程彼此共享堆內(nèi)存并保有他們自己獨(dú)自的?臻g。這也是為什么當(dāng)一個(gè)線程調(diào)用一個(gè)方法時(shí),他的.局部變量可以保證線程安全。但堆內(nèi)存并不是線程安全的,必須通 過(guò)顯示的聲明同步來(lái)確保線程安全。
問題:列舉幾種不同的創(chuàng)建線程的方法.
解答:可以通過(guò)如下幾種方式:
• 繼承Thread 類
• 實(shí)現(xiàn)Runnable 接口
• 使用Executor framework (這會(huì)創(chuàng)建一個(gè)線程池)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15class
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.
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class
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.
}
}
通過(guò)線程池來(lái)創(chuàng)建更有效率,
資料共享平臺(tái)
《Java多線程常見面試問題及解答》(http://www.ishadingyu.com)。問題:推薦通過(guò)哪種方式創(chuàng)建線程,為什么?
解答:最好使用Runnable接口,這樣你的類就不必繼承Thread類,不然當(dāng)你需要多重繼承的時(shí)候,你將 一籌莫展(我們都知道Java中的類只能繼承自一個(gè)類,但可以同時(shí)實(shí)現(xiàn)多個(gè)接口)。在上面的例子中,因?yàn)槲覀円^承Base類,所以實(shí)現(xiàn)Runnable 接口成了顯而易見的選擇。同時(shí)你也要注意到在不同的例子中,線程是如何啟動(dòng)的。按照面向?qū)ο蟮姆椒ㄕ,你?yīng)該只在希望改變父類的行為的時(shí)候才去繼承他。通 過(guò)實(shí)現(xiàn)Runnable接口來(lái)代替繼承Thread類可以告訴使用者Counter是Base類型的一個(gè)對(duì)象,并會(huì)作為線程執(zhí)行。
問題:簡(jiǎn)要的說(shuō)明一下高級(jí)線程狀態(tài).
解答:下圖說(shuō)明了線程的各種狀態(tài).
• 可執(zhí)行(Runnable):當(dāng)調(diào)用start()方法后,一個(gè)線程變?yōu)榭蓤?zhí)行狀態(tài),但是并不意味著他會(huì)立刻開始真正地執(zhí)行。而是被放入線程池,
【Java多線程常見面試問題及解答】相關(guān)文章:
3.常見面試問題解答