如何创建三个线程的循环交换?

时间:2013-05-22 20:21:53

标签: java multithreading

如何创建三个线程的循环交换?那就是:第一个线程必须将数据发送到第二个第二个第三个​​第三个​​线程必须先将数据发送到

我写了一些代码,但线程随机交换。

class DataClass {

    int value;
    String message;

    DataClass(int v, String s) {
        value = v;
        message = s;
    }

    int getValue() {
        return (value);
    }

    String getMassage() {
        return (message);
    }
}

class Loop implements Runnable {

    int counter;
    String name;
    Exchanger<DataClass> exchanger;

    Loop(int startValue, String id, Exchanger<DataClass> ex) {
        counter = startValue;
        name = id;
        exchanger = ex;
        System.out.println(name + ": created");
    }

    public void run() {
        System.out.println(name + ": started");

        DataClass data = new DataClass(counter, name);

        for (int i = 0; i < 3; ++i) {
            try {
                DataClass newData = exchanger.exchange(data);
                counter += newData.getValue();

                System.out.println(name + ": from "
                        + newData.getMassage() + ": data: "
                        + newData.getValue() + ": state = " + counter);

            } catch (InterruptedException e) {
                System.err.println(e.toString());
            }
        }
        System.out.println(name + ": ended");
    }
}

public class ExchangerDemo {

    public static void main(String args[]) {
        System.out.println("Main process started");
        Exchanger<DataClass> exchanger = new Exchanger<DataClass>();
        Loop loop1 = new Loop(1, "First", exchanger);
        Loop loop2 = new Loop(2, "Second", exchanger);
        Loop loop3 = new Loop(3, "Third", exchanger);
        new Thread(loop1).start();
        new Thread(loop2).start();
        new Thread(loop3).start();
        System.out.println("Main process ended");
    }
}

1 个答案:

答案 0 :(得分:0)

对于您的依赖项,您应该创建三个类,并且有三个不同的Exchange对象(每个对应一个)。因此,thread1将介于1和2之间(输出为1到2),线程2将介于2和3之间,并且线程3的呼出将位于其自身和1之间。请记住,交换器只会保护它直到它从其馈线输入,直到它传递给它的接收器。

同步也不像书中那么糟糕。用它。观看http://www.youtube.com/watch?v=WTVooKLLVT8

也可参考Best way of running two threads alternatively?

为什么你需要三个线程?你可以使用线程池并将每项任务分配给3件事吗?