多執行緒按順序列印

2021-10-10 02:19:37 字數 3230 閱讀 5631

**於leetcode1114

我們提供了乙個類:

public class foo

public void second()

public void third()

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

請設計修改程式,以確保 second() 方法在 first() 方法之後被執行,third() 方法在 second() 方法之後被執行。

本文提供四種方法reentrantlock,wait-notify,semaphore,cas自旋。其他方法還可以用countdownlatch,arrayblockingqueue。

//第一種方法用reentrantlock

class

foopublic

void

first

(runnable printfirst)

throws interruptedexception

}// printfirst.run() outputs "first". do not change or remove this line.

printfirst.

run();

flag =2;

reentrantlock.

unlock()

;}public

void

second

(runnable printsecond)

throws interruptedexception

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

printsecond.

run();

flag =3;

reentrantlock.

unlock()

;}public

void

third

(runnable printthird)

throws interruptedexception

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

printthird.

run();

reentrantlock.

unlock()

;}}

//既然都volatile的flag了,直接下面這麼寫

class

foopublic

void

first

(runnable printfirst)

throws interruptedexception

// printfirst.run() outputs "first". do not change or remove this line.

printfirst.

run();

flag =2;

}public

void

second

(runnable printsecond)

throws interruptedexception

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

printsecond.

run();

flag =3;

}public

void

third

(runnable printthird)

throws interruptedexception

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

printthird.

run();

}}

//wait-notify

class

foopublic

void

first

(runnable printfirst)

throws interruptedexception

// printfirst.run() outputs "first". do not change or remove this line.

printfirst.

run();

flag =2;

object.

notifyall()

;}}public

void

second

(runnable printsecond)

throws interruptedexception

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

printsecond.

run();

flag =3;

object.

notifyall()

;}}public

void

third

(runnable printthird)

throws interruptedexception

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

printthird.

run();

object.

notifyall()

;}}}

//訊號量

class

foopublic

void

first

(runnable printfirst)

throws interruptedexception

public

void

second

(runnable printsecond)

throws interruptedexception

public

void

third

(runnable printthird)

throws interruptedexception

}

多執行緒 LeetCode 按序列印

我們提供了乙個類 public class foo public void two public void three 三個不同的執行緒將會共用乙個 foo 例項。執行緒 a 將會呼叫 one 方法 執行緒 b 將會呼叫 two 方法 執行緒 c 將會呼叫 three 方法請設計修改程式,以確保 t...

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 方法 請設計修...