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

后端 未结 4 1154
独厮守ぢ
独厮守ぢ 2021-01-02 18:49

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

Something similar to a comme

4条回答
  •  孤独总比滥情好
    2021-01-02 19:40

    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 queue = new LinkedBlockingQueue();
            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);
            }
        }
    }
    

提交回复
热议问题