多執行緒 LeetCode 按序列印

2021-10-03 11:05:54 字數 2275 閱讀 3061

我們提供了乙個類:

public class foo 

public void two()

public void three()

}

三個不同的執行緒將會共用乙個 foo 例項。

執行緒 a 將會呼叫 one() 方法

執行緒 b 將會呼叫 two() 方法

執行緒 c 將會呼叫 three() 方法

請設計修改程式,以確保 two() 方法在 one() 方法之後被執行,three() 方法在 two() 方法之後被執行。

示例 1:

輸入: [1,2,3]

輸出: 「onetwothree」

解釋:有三個執行緒會被非同步啟動。

輸入 [1,2,3] 表示執行緒 a 將會呼叫 one() 方法,執行緒 b 將會呼叫 two() 方法,執行緒 c 將會呼叫 three() 方法。

正確的輸出是 「onetwothree」。

示例 2:

輸入: [1,3,2]

輸出: 「onetwothree」

解釋:輸入 [1,3,2] 表示執行緒 a 將會呼叫 one() 方法,執行緒 b 將會呼叫 three() 方法,執行緒 c 將會呼叫 two() 方法。

正確的輸出是 「onetwothree」。

注意:儘管輸入中的數字似乎暗示了順序,但是我們並不保證執行緒在作業系統中的排程順序。

你看到的輸入格式主要是為了確保測試的全面性。

1、構造執行屏障

主要思想:構造執行屏障,執行緒2等待執行緒1執行結束,執行緒3等待執行緒2執行結束,保證執行順序。

class

foopublic

void

first

(runnable printfirst)

throws interruptedexception

public

void

second

(runnable printsecond)

throws interruptedexception

public

void

third

(runnable printthird)

throws interruptedexception

}

2、使用synchronization
class

foopublic

void

first

(runnable printfirst)

throws interruptedexception

}public

void

second

(runnable printsecond)

throws interruptedexception

// printsecond.run() outputs "second". do not change or remove this line.

printsecond.

run();

secondfinished =

true

; lock.

notifyall()

;}}public

void

third

(runnable printthird)

throws interruptedexception

// printthird.run() outputs "third". do not change or remove this line.

printthird.

run();

}}}

3、使用volatile
class

foovolatile

int count=1;

public

void

first

(runnable printfirst)

throws interruptedexception

public

void

second

(runnable printsecond)

throws interruptedexception

public

void

third

(runnable printthird)

throws interruptedexception

}

多執行緒按順序列印

於leetcode1114 我們提供了乙個類 public class foo public void second public void third 三個不同的執行緒將會共用乙個 foo 例項。請設計修改程式,以確保 second 方法在 first 方法之後被執行,third 方法在 seco...

1114 按序列印 多執行緒

難度簡單237 我們提供了乙個類 public class foo public void second public void third 三個不同的執行緒 a b c 將會共用乙個foo例項。請設計修改程式,以確保second 方法在first 方法之後被執行,third 方法在second 方...

20 12 31 1114 按序列印 多執行緒

我們提供了乙個類 public class foo public void second public void third 三個不同的執行緒將會共用乙個 foo 例項。執行緒 a 將會呼叫 first 方法 執行緒 b 將會呼叫 second 方法 執行緒 c 將會呼叫 third 方法 請設計修...