Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameter to an already running thread in java?

How to pass parameter to an already running thread in java -- not in the constructor, & probably without using wait() (possible ??)

Something similar to a comment in How can I pass a parameter to a Java Thread?

Do you mean passing a parameter to an already running thread ? Because all the current answers are about passing parameters to new threads... – Valentin Rocher May 18 '09 at 10:43

[edited]

yes, I was looking for something like the producer/consumer pattern.

I wanted something like a thread in which has the processing & is ready for keyboard input. The other thread is just to monitor network and pass on the received text to the processing thread.

like image 898
maan81 Avatar asked Aug 21 '12 06:08

maan81


2 Answers

Maybe what you really need is blocking queue.When you create the thread, you pass the blocking queue in and the thread should keep checking if there is any element in the queue. Outside the thread, you can put elements to the queue while the thread is "running". Blocking queue can prevent the thread from quit if their is nothing to do.

public class Test {
    public static void main(String... args) {

        final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
        Thread running = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        String data = queue.take();
                        //handle the data
                    } catch (InterruptedException e) {
                        System.err.println("Error occurred:" + e);
                    }
                }
            }
        });

        running.start();
        // Send data to the running thread
        for (int i = 0; i < 10; i++) {
            queue.offer("data " + i);
        }
    }
}
like image 62
George Avatar answered Sep 24 '22 10:09

George


The "other thread" will have its own life, so you can't really communicate with it / pass parameters to it, unless it actively reads what you gives to it.

A thread which you allows you to communicate with it typically reads data from some buffered queue.

Have a look at ArrayBlockingQueue for instance, and read up on the Consumer-Producer pattern.

like image 39
aioobe Avatar answered Sep 21 '22 10:09

aioobe