是否可以在hashmap中存储线程对象?

问题描述 投票:0回答:1

我有一个场景,我调用大约10个

Thread
,每个
Thread
必须等到
Notifier
类通知我想要通知特定的
Thread
,我正在做的是我正在使用
HashMap
Thread
id 为
key
Thread
实例为值。后来在
Notifier
中,我尝试通过遍历地图
map.get(threadId)
来通知它,它给出了
Thread
实例,我试图对此调用通知,但它抛出了
IllegalmonitorException
。我不确定要同步什么,无论是
HashMap
Thread
类中的
Waiter
还是
Notifier
..

package com.cgi.sample.jms.requestor;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RequestorApplication {
    private final Object lock = new Object();
    public static String correlationId;

    public static String getCorrelationId() {
        correlationId = UUID.randomUUID().toString();
        return correlationId;
    }

    public static void main(String args[]) throws Exception {

        Map<Long, Thread> map = new HashMap<Long, Thread>();

        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 2; i++) {

            Waiter waiter = new Waiter(map);

            executor.execute(waiter);

            Notifier notifier = new Notifier(map);
            executor.execute(notifier);
        }

        System.out.println("All the threads are started");
    }
}

class Waiter implements Runnable {

    Map<Long, Thread> map;
    ExecutorService executor = Executors.newFixedThreadPool(5);

    public Waiter(Map<Long, Thread> map) {
        this.map = map;
    }

    public void run() {

        ExecutorService executor = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 2; i++) {

            Runner instance = new Runner();

            System.out.println("Executing thread " + " with " + Thread.currentThread().getName());

            long threadId = Thread.currentThread().getId();

            String threadname = Thread.currentThread().getName();

            executor.execute(instance);

            synchronized (map) {

                map.put(threadId, Thread.currentThread());

                try {
                    instance.wait();
                    System.out.println(threadname + "  Thread entered into waiting state!!!");
                    // Thread.currentThread().wait();
                    System.out.println(threadname + "  Thread woke up from wait!!!!!");

                } catch (InterruptedException e) {

                    e.printStackTrace();
                }
            }
        }

    }

}

class Notifier implements Runnable {

    Map<Long, Thread> map;

    public Notifier(Map<Long, Thread> map)

    {
        this.map = map;
    }

    public synchronized void run() {

        synchronized (map) {

            for (Map.Entry<Long, Thread> entry : map.entrySet()) {

                System.out.println("stored threads in map are--->" + map.get(entry.getKey()));

                map.get(entry.getKey()).notify();

            }

        }
    }
}

class Runner implements Runnable {

    public void run() {
        System.out.println("runner invoked");

    }
}
java multithreading collections concurrency
1个回答
2
投票

您问题的答案是:。因为线程是一个对象,它可以存储到HashMap中。

另外,@T.J.Crowder 告诉你,你使用通知的方式是错误的。这是因为您正在对没有线程锁的对象调用 notify (map.get(entry.getKey()).notify();

)。相反,您应该调用拥有线程锁的对象 
notify
 (
Runner
) 的 
instance.notify()
,正如您的代码向我们展示的那样:
instance.wait();
 

首先!您必须同步阻塞对象

instance

,该对象将使用 
wait
 方法阻塞线程,例如: 

synchronized(instance){ try{ instance.wait() }catch(...) { //Do Something else } }

然后,调用对象

notify

 的方法 
Runner
 来停止等待并继续线程并离开同步块,如下所示: 

map.get(entry.getKey()).getRunnerInstance().notify();



但是,请考虑一下,用您当前的代码很难实现这些技巧,因为您必须重写几个部分,例如:

您使用位于 for 循环上下文中的对象来阻塞线程的代码

for (int i = 0; i < 2; i++) { Runner instance = new Runner(); //... synchronized (map) { map.put(threadId, Thread.currentThread()); try { instance.wait(); //You are blocking over a instance declared into the For Loop. }catch(..){ //.. }; } }
    
© www.soinside.com 2019 - 2024. All rights reserved.