Closed. This question does not meet Stack Overflow guidelines。它当前不接受答案。












想改善这个问题吗?更新问题,以使为on-topic

6年前关闭。



Improve this question





您好,有一个聪明的堆栈溢出社区!

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

我如何像在B类中一样在C类中接收相同的数据?

最佳答案

这是您的A(可运行)

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(主)

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(工友)

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]


希望这就是你想要的

10-05 18:42