如何让N Threads在Java中以循环方式轮流?

时间:2015-10-06 06:22:22

标签: java multithreading

我最近在Stackoverflow上遇到了这个问题,问题是在两个线程中打印偶数和奇数,这样它们以递增顺序打印。问题是here,我提供了一个解决方案。这让我想到,如果我们需要N个线程以预定顺序以循环方式轮流转换,我们应该怎么做?我尝试使用CyclicBarrier。这是我的代码:

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class NThreadTurnTaking {

public static void main(String[] args) {
    NThreadTurnTaking nThreadTurnTaking =  new NThreadTurnTaking();
    CyclicBarrier cyclicBarrier =  new CyclicBarrier(3);
    NThreadTurnTaking.A  a = nThreadTurnTaking.new A(cyclicBarrier);
    NThreadTurnTaking.B  b = nThreadTurnTaking.new B(cyclicBarrier);
    NThreadTurnTaking.C  c = nThreadTurnTaking.new C(cyclicBarrier);
    Thread t1  =  new Thread(a);
    Thread t2  =  new Thread(b);
    Thread t3  =  new Thread(c);
    t1.start();
    t2.start();
    t3.start();     
}

class A implements Runnable{
    private final CyclicBarrier cyclicBarrier;

    public A(CyclicBarrier cyclicBarrier) {
        super();
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("A");
            try {
                cyclicBarrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }

    }
}
class B implements Runnable{
    private final CyclicBarrier cyclicBarrier;

    public B(CyclicBarrier cyclicBarrier) {
        super();
        this.cyclicBarrier = cyclicBarrier;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("B");
            try {
                cyclicBarrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
}
class C implements Runnable{
    private final CyclicBarrier cyclicBarrier;

    public C(CyclicBarrier cyclicBarrier) {
        super();
        this.cyclicBarrier = cyclicBarrier;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("C");
            try {
                cyclicBarrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }
}
}

我希望我的程序按顺序打印A-&gt; B-&gt; C.虽然使用CyclicBarrier可以确保它们一个接一个地打印,但订单没有被维护,这很明显,因为我没有做任何特别的事情来告诉我的程序我想要一个特定的订单。这是输出:

  

乙   C   一个   一个   C   乙   乙   一个   Ç.....

那么,我们如何确保订单呢?请帮助。

0 个答案:

没有答案