Java 多執行緒

2021-07-31 22:26:52 字數 1988 閱讀 7434

這是類的宣告部分,並繼承自thread執行緒類,在裡面實現了執行緒的run()方法

public

class

******thread

extends

thread

//run()方法是在實現thread類的過程中一定要實現的方法

public

void

run() }}

這裡我們例項化該類,並使用start()方法啟動執行緒

public

static

void

main(string args)

}

上述示例結果為:

我們可以發現,執行的結果與我們定義的順序並不一致,並不是

thread 1

thread 1(5)

thread 1(4)

thread 1(3)

thread 1(2)

thread 1(1)

thread 2

thread 2(5)

thread 2(4)

thread 2(3)

thread 2(2)

thread 2(1)

這說明cpu處理乙個現有執行緒集的順序是不確定的。

public

class

timerprinter

implements

runnable

//run函式作為runnable介面要實現出來

public

void

run() catch(exception e) }}

}

這裡將當前類的例項作為thread類的構造引數,以此建立執行緒物件

注意:當使用runnable介面時,不能像繼承thread類那樣直接建立所需物件並執行,必須從thread類的乙個例項內部執行。

執行緒

例項化方式

thread

new ******thread(i).start()

runnable

thread t1 = new thread(new timerprinter(1000, 「thread 1」));

t1.start();

新建狀態:執行緒已經被建立但尚未執行(即未呼叫start()方法)

就緒狀態:執行緒已經被建立(即已經處於新建狀態)後,執行start()方法,該狀態的執行緒位於可執行執行緒池中,變得可執行,等待獲取cpu的使用權。

執行狀態:就緒狀態的執行緒獲取了cpu,執行程式**(即run()方法)

阻塞狀態:程式因某種原因不會被分配cpu,無法繼續執行。

死亡狀態:執行緒run()方法執行完了或者因異常退出了run()方法,該執行緒結束生命週期

其中阻塞狀態可以由下面5種原因導致:

java多執行緒

在網上看到很有意思的問題,摘下來好好看下 在面試的時候被問了乙個多執行緒的問題 回來仔細思考了一下,多執行緒是否真的能提高了效率?我對多執行緒的理解就是 比如挖乙個隧道,有2種開工方法 1 只在山的一頭挖,直至挖到山的另一頭,從而打通隧道,這可以看成是單執行緒 2 在山的兩頭挖,同時開工,最後在山的...

Java 多執行緒

1。thread類和runnable介面 2。主線程 用thread的static thread currentthread 方法獲得 3。通過實現runnable介面建立執行緒 實現runnable介面的run方法。新執行緒在run 方法返回時結束。注意用這種方法建立程序時,在實現runnable...

JAVA 多執行緒

為hashmap的不正確使用所導致。hashmap在多執行緒環境下使用不安全。使用靜態hashmap作為聯絡人資料快取,key為手機號碼.private static maplxrdata new hashmap 多執行緒環境下不同步hashmap可能導致如下問題 1 多執行緒put操作後可能導致g...