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

时间:2014-04-04 09:48:43

标签: java multithreading shared-memory runnable

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

简单示例:

Hashtable

主题1: 添加到Hashtable Key1 Keyvalue1

主题2: 添加到Hashtable Key2 Keyvalue2

主题3: 添加到Hashtable Key3 Keyvalue3

on join print hashtable

非常感谢任何帮助,

谢谢

2 个答案:

答案 0 :(得分:4)

那么你想要的是一个由多个线程编辑的单个HashTable?应该有3个线程,每个人都应该在表中放入一个不同的密钥和一个不同的值,每次放置后,活动线程应成对打印出所有的密钥和值?我对吗?因为如果,这可能是:

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) {
            }
        }

    }
}

答案 1 :(得分:1)

您需要使用信号量进行同步。这是一个例子:{{3p>