multithreading - Java Multi thread messaging -
i have app 2 threads, 1 writes queue , second 1 read async it. need create third 1 generate 20 more. newly created threads run till explicitly stopped. 20 threads should "live" data in order analyze it. each of 20 has unique id/name. need send relevant data (that read thread collect) correct thread (of 20 threads). e.g. if data include string id (in it) of 2 --> need send thread id =2. question is: how should hold "pointer" each of 20 threads , send relevant data? (i can search id in runnable list (that hold threads)--> need call method "newdata(string)" in order send data running thread). how should it? tia paz
you better use queue communicate threads. put of queues in map easy access. recommend blockingqueue
.
public class test { // special stop message tell worker stop. public static final message stop = new message("stop!"); static class message { final string msg; // message worker. public message(string msg) { this.msg = msg; } public string tostring() { return msg; } } class worker implements runnable { private volatile boolean stop = false; private final blockingqueue<message> workqueue; public worker(blockingqueue<message> workqueue) { this.workqueue = workqueue; } @override public void run() { while (!stop) { try { message msg = workqueue.poll(10, timeunit.seconds); // handle message ... system.out.println("worker " + thread.currentthread().getname() + " got message " + msg); // special stop message. if (msg == stop) { stop = true; } } catch (interruptedexception ex) { // stop on interrupt. stop = true; } } } } map<integer, blockingqueue<message>> queues = new hashmap<>(); public void test() throws interruptedexception { // keep track of threads. list<thread> threads = new arraylist<>(); (int = 0; < 20; i++) { // make queue it. blockingqueue<message> queue = new arrayblockingqueue(10); // build thread, handing queue use. thread thread = new thread(new worker(queue), "worker-" + i); threads.add(thread); // store queue in map. queues.put(i, queue); // start process. thread.start(); } // test one. queues.get(5).put(new message("hello")); // close down. (blockingqueue<message> q : queues.values()) { // stop each queue. q.put(stop); } // join threads wait them finish. (thread t : threads) { t.join(); } } public static void main(string args[]) { try { new test().test(); } catch (throwable t) { t.printstacktrace(system.err); } } }
Comments
Post a Comment