【发布时间】:2014-11-27 17:18:28
【问题描述】:
在一次采访中被问到这个问题,试图解决它......但没有成功。 我想到了使用 CyclicBarrier
共有三个线程 T1 打印 1,4,7... T2 打印 2,5,8... 而 T3 打印 3,6,9 ...。怎么同步这三个来打印序列1,2,3,4,5,6,7,8,9....
我尝试编写和运行以下代码
public class CyclicBarrierTest {
public static void main(String[] args) {
CyclicBarrier cBarrier = new CyclicBarrier(3);
new Thread(new ThreadOne(cBarrier,1,10,"One")).start();
new Thread(new ThreadOne(cBarrier,2,10,"Two")).start();
new Thread(new ThreadOne(cBarrier,3,10,"Three")).start();
}
}
class ThreadOne implements Runnable {
private CyclicBarrier cb;
private String name;
private int startCounter;
private int numOfPrints;
public ThreadOne(CyclicBarrier cb, int startCounter,int numOfPrints,String name) {
this.cb = cb;
this.startCounter=startCounter;
this.numOfPrints=numOfPrints;
this.name=name;
}
@Override
public void run() {
for(int counter=0;counter<numOfPrints;counter++)
{
try {
// System.out.println(">>"+name+"<< "+cb.await());
cb.await();
System.out.println("["+name+"] "+startCounter);
cb.await();
//System.out.println("<<"+name+">> "+cb.await());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
startCounter+=3;
}
}
}
输出
[Three] 3
[One] 1
[Two] 2
[One] 4
[Two] 5
[Three] 6
[Two] 8
[One] 7
[Three] 9
[One] 10
[Two] 11
[Three] 12
[Two] 14
[One] 13
[Three] 15
[One] 16
[Two] 17
[Three] 18
[Two] 20
[One] 19
[Three] 21
[One] 22
[Two] 23
[Three] 24
[Two] 26
[One] 25
[Three] 27
[One] 28
[Two] 29
[Three] 30
谁能帮我正确回答?
类似的问题 Thread Synchronization - Synchronizing three threads to print 012012012012..... not working
【问题讨论】:
-
如何与传递给构造函数的 AtomicInteger 共享您尝试打印的当前数字。如果这是当前线程无法打印的数字,它只是再次阻塞在屏障上?
-
这个问题已经回答了:stackoverflow.com/a/41671224/3233586
标签: java multithreading java.util.concurrent