gpt4 book ai didi

Java Runnable多线程在线程之间共享中心对象

转载 作者:行者123 更新时间:2023-11-29 07:48:57 25 4
gpt4 key购买 nike

我正在寻找一个简单的 Java Runnable 示例,其中 3 个单独的线程分别将一个项目添加到所有线程都可用的哈希表中,并在线程完成时显示。

简单的例子:

哈希表

线程 1:添加到哈希表 Key1 Keyvalue1

线程 2:添加到哈希表 Key2 Keyvalue2

线程 3:添加到哈希表 Key3 Keyvalue3

关于加入打印哈希表

任何帮助将不胜感激,

谢谢

最佳答案

那么你想要的是由多个线程编辑的单个哈希表?应有 3 个线程,每个人都应将不同的键和不同的值放入表中,每次放置后, Activity 线程应成对打印出所有键和值?我对吗?因为如果,这可能是:

import java.util.Hashtable;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;

public class Threadexample {

// Hashtable and Keylist
private Hashtable<String, Integer> table;
private CopyOnWriteArrayList<String> keys;

// Konstruktor
public Threadexample() {
table = new Hashtable<String, Integer>();
keys = new CopyOnWriteArrayList<String>();
}

// Adds an Item to the Table and prints the table
public synchronized void addItem(String key, int value, String threadname) {
// Adding
table.put(key, value);
if (!isAlreadyAdded(key)) {
keys.add(key);
}else{
return;
}
System.out.println(threadname + "-> Added! Key: " + key + " Value: " + value);
// Showing
showItems(threadname);
}

// Bewares of doublicate keys in the keylist
private boolean isAlreadyAdded(String key) {
int size = keys.size();
for (int i = 0; i < size; i++) {
if (keys.get(i).equals(key)) {
return true;
}
}
return false;
}

// Prints out all Integer with their keys
private void showItems(String threadname) {
Set<String> keys = table.keySet();
for (String key : keys) {
System.out.println(threadname + "-> Key: " + key + " Value: " + table.get(key));
}
System.out.print(System.getProperty("line.separator"));
}

// Mainmethod
public static void main(String[] args) {
final Threadexample tex = new Threadexample();
final String[] keyarray = new String[] { "Zero", "One", "Two" };

// starts 3 Threads which are adding and showing the Objects
for (int i = 0; i < 3; i++) {
final int value = i;

new Thread() {
public void run() {
setName("Thread: " + (value + 1));
tex.addItem(keyarray[value], value, getName());
}
}.start();

try {
// Leave every Thread enough time to work
Thread.sleep(10);
} catch (InterruptedException e) {
}
}

}
}

关于Java Runnable多线程在线程之间共享中心对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22859292/

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