[英]Java - the thread execution order
我正在嘗試使用信號量嚴格依次啟動 10 個線程。 也就是說,在thread-0執行之后,應該執行thread-1,而不是thread-2。
但問題是線程到達semaphore.acquire()
- 方法時是無序的,因此線程的執行是無序的。 如何使用信號量但不使用thread.join()
來解決這個問題?
public class Main {
private Semaphore semaphore = new Semaphore(1, true);
public static void main(String[] args) {
new Main().start();
}
private void start() {
for (int i = 0; i < 10; i++) {
Runnable runnable = () -> {
try {
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("In run method " + Thread.currentThread().getName());
semaphore.release();
};
Thread thread = new Thread(runnable);
thread.start();
}
}
}
Output:
In run method Thread-0
In run method Thread-1
In run method Thread-4
In run method Thread-5
In run method Thread-3
In run method Thread-2
In run method Thread-6
In run method Thread-7
In run method Thread-9
In run method Thread-8
您需要具有某種排序概念的同步 object。 如果您熟悉美國雜貨店,請考慮熟食櫃台上的“取號”設備,它會告訴您輪到誰了。
粗略的代碼草圖:
class SyncThing {
int turn = 0;
synchronized void waitForTurn(int me) {
while (turn != me)
wait();
}
synchronized void nextTurn() {
turn++;
notifyAll();
}
}
然后聲明SyncThing syncThing = new SyncThing();
並運行第 i 個線程:
Runnable runnable = () -> {
syncThing.waitForTurn(i);
System.out.println("In run method " + Thread.currentThread().getName());
syncThing.nextTurn();
};
這是在我的腦海中輸入的,並沒有作為完整的代碼提供,但它應該顯示方式。
private void start() {
final AtomicInteger counter = new AtomicInteger();
for (int i = 0; i < 10; i++) {
final int num = i;
new Thread(() -> {
while (counter.get() != num) {
}
System.out.println("In run method " + Thread.currentThread().getName());
counter.incrementAndGet();
}).start();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.