Java线程将相同的数据发送到多个类

时间:2013-12-05 21:17:50

标签: java multithreading

你好有Stack Overflow的明智社区!

我有一个相当简单的问题:假设我们有A,B和C类.A类实现Runnable,B类启动线程。

我怎样才能在C级接收相同的数据,就像我在B级那样?

1 个答案:

答案 0 :(得分:1)

这是你的A(Arunnable)

import java.util.Date;
import java.util.ArrayList;
import java.util.Iterator;

public class Arunnable implements Runnable {
    ArrayList<Bmain> subscribers = new ArrayList<Bmain>();
    public void run() {
        try {
            for (;;) {
                Thread.sleep(1000);
                String message = String.format("Hi! from Arunnable, now is %d", (new Date()).getTime());
                Iterator<Bmain> iter = subscribers.iterator();
                while (iter.hasNext()) {
                    Bmain o = iter.next();
                    o.publish(message);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void subscribe(Bmain o) {
        subscribers.add(o);
    }
}

这是你的B(Bmain)

import java.util.concurrent.ArrayBlockingQueue;

public class Bmain {
    ArrayBlockingQueue<String> messageQueue;
    Bmain() {
        messageQueue = new ArrayBlockingQueue<String>(10 /* capacity */, true /* fair? */);
    }
    public void doit() {
        Arunnable ar = new Arunnable();
        Thread a = new Thread(ar);
        a.setDaemon(false);
        a.start();

        Thread b = new Thread(new Cworker(ar));
        b.setDaemon(false);
        b.start();

        ar.subscribe(this);
        loop("Bmain  ");
    }
    public static void main(String[] args) {
        (new Bmain()).doit();
    }
    public void publish(String msg) {
        try {
            messageQueue.put(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void loop(String who) {
        try {
            for (;;) {
                String s = messageQueue.take();
                System.out.printf("%s got [%s]\n", who, s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这是你的C(Cworker)

public class Cworker extends Bmain implements Runnable {
    Arunnable a;
    Cworker(Arunnable a) {
        this.a = a;
        a.subscribe(this);
    }
    public void run() {
        loop("Cworker");
    }
}

这里我得到了以下输出

Cworker got [Hi! from Arunnable, now is 1386281579391]
Bmain   got [Hi! from Arunnable, now is 1386281579391]
Cworker got [Hi! from Arunnable, now is 1386281580396]
Bmain   got [Hi! from Arunnable, now is 1386281580396]
Cworker got [Hi! from Arunnable, now is 1386281581396]
Bmain   got [Hi! from Arunnable, now is 1386281581396]
Cworker got [Hi! from Arunnable, now is 1386281582397]
Bmain   got [Hi! from Arunnable, now is 1386281582397]
Cworker got [Hi! from Arunnable, now is 1386281583397]
Bmain   got [Hi! from Arunnable, now is 1386281583397]

希望这是你想要的