我正在尝试使用可运行接口(interface)学习多线程,但在弄清楚如何传递信息方面遇到了一些麻烦。基本上,在下面的示例中,我想从 HashMap 中删除静态引用,但如果这样做,程序就会中断。如何在不使用 static 关键字的情况下将 hashmap 传递给可运行的接口(interface)类?
public class ThreadDemo {
static HashMap <String, Integer>map = new HashMap<>();
public String Hi() {
return "hi";
}
public String Hello() {
return "Hello";
}
public void addToMap(String item) {
if (map.containsKey(item)) {
map.put(item, map.get(item) + 1);
} else {
map.put(item, 1);
}
}
public static void main(String[] args) throws InterruptedException {
ArrayList<Thread> all = new ArrayList<>();
for (int i = 0; i < 50; ++i) {
threader threader = new threader();
all.add(new Thread(threader));
}
for (Thread thread : all) {
thread.start();
}
for (Thread thread : all) {
thread.join();
}
ThreadDemo td = new ThreadDemo();
System.out.println(td.map);
}
}
还有一个实现 Runnable 的类
public class threader implements Runnable {
ThreadDemo td = new ThreadDemo();
@Override
public void run() {
synchronized(td.map) {
td.addToMap(td.Hi());
td.addToMap(td.Hello());
}
}
}
最佳答案
类实例都是关于信息的。
public class threader implements Runnable {
final private ThreadDemo td;
public threader(ThreadDemo td) {
this.td = td;
}
@Override
public void run() {
..
}
}
然后使用(详细内容省略,只是思路):
ThreadDemo theTd = new ThreadDemo();
for (...) {
threader threader = new threader(theTd);
all.add(new Thread(threader));
}
....
当然,所有线程都使用相同的 ThreadDemo,具有相同的映射,因此您需要确保访问以某种方式互锁,例如,通过使用synchronized
。在此示例中,应该同步 ThreadDemo.addToMap
方法,而不是 addToMap
的调用者。这将“照顾 map ”的责任交给了实际拥有 map 的地方,因此是一个更好的设计。
我选择共享 ThreadDemo,而不仅仅是共享 ThreadDemo 内的 map ,因为在我看来,ThreadDemo 的目的只是作为 map 的包装器。
关于没有静态引用的 Java Runnable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67528242/