![](/img/trans.png)
[英]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.