gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:45:17 25 4
gpt4 key购买 nike

您好,Stack Overflow 明智的社区!

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

如何在 C 类中接收与 B 类中相同的数据?

最佳答案

这是您的 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 (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]

希望这是你想要的

关于Java线程向多个类发送相同的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20410919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com