[英]How to I make threads starts their work in order of their IDs (using semaphores)?
[英]How to make threads work in order using CountDownlatch?
我正在學習如何在Java中使用countdownLatch,並創建了一個簡單的示例,如下代碼所示。
我從該機制中學到的是,這只是一種強制僅一個線程等待他人完成工作的方法,然后,正在等待的線程將在其他線程完成后開始工作。
我的問題是,如果我有4個線程“ t1,t2,t3和t4”,怎么辦?它們應該按所述順序啟動,並且每個線程應該在前一個/上一個線程結束時啟動。 換句話說,t2應該等待t1並在t1完成時開始,t3應該等待t2並在t2完成時開始,t4應該等待t3並在t3完成時開始。
1-如何使用CountDownLatch和循環屏障?
2-傳遞給CountDownLatch類的構造函數的countDown參數是否應表示等待的線程數?
代碼 :
public class MainClass {
public static void main(String[] args) {
CountDownLatch latch1 = new CountDownLatch(1);
Thread t1 = new Thread(new AscendingOrder(latch1));
Thread t2 = new Thread(new DescendingOrder(latch1));
t1.start();
t2.start();
}
static class AscendingOrder implements Runnable {
private CountDownLatch latch;
public AscendingOrder(CountDownLatch latch) {
// TODO Auto-generated constructor stub
this.latch = latch;
}
public void run() {
// TODO Auto-generated method stub
System.out.println("thread t1 started.");
for (int i = 0; i < 10; i++)
System.out.println(i);
this.latch.countDown();
}
}
static class DescendingOrder implements Runnable {
private CountDownLatch latch;
public DescendingOrder(CountDownLatch latch1) {
// TODO Auto-generated constructor stub
this.latch = latch1;
}
public void run() {
// TODO Auto-generated method stub
System.out.println("thread t2 started and waiting");
try {
this.latch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 10; i > 0; i--)
System.out.println(i);
}
}
}
1-如何使用CountDownLatch和循環屏障?
CyclicBarrier對於這個問題不是很理想,我已經寫過比較這兩個的帖子,請在這里看看
public class CountDownLatchTest {
public static void main(String[] args) {
CountDownLatch first = new CountDownLatch(1);
CountDownLatch prev = first;
for(int i=0;i<10;i++) {
CountDownLatch next = new CountDownLatch(1);
new TestThread(prev, next, i).start();
prev = next;
}
first.countDown();
}
public static class TestThread extends Thread {
private CountDownLatch prev;
private CountDownLatch next;
private int id;
public TestThread(CountDownLatch prev, CountDownLatch next, int id) {
this.prev = prev;
this.next = next;
this.id = id;
}
public void run() {
if (prev != null) {
try {
prev.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
doWork();
} finally {
if (next != null) {
next.countDown();
}
}
}
public void doWork() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Work done in Thread : "
+ id);
}
}
}
2-傳遞給CountDownLatch類的構造函數的countDown參數是否應表示等待的線程數?
CountDownLatch.await()將一直等到CountDownLatch.countDown()方法被調用了countDown參數次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.