How to pass parameter to already running thread in java?

How to pass parameter to already running thread in java - not in the constructor, and, possibly, without using wait () (maybe ??)

Something similar to a comment in How to pass a parameter to a Java thread?

Do you mean passing a parameter to an already running thread? Because all current answers relate to passing parameters to new threads ... - Valentin Rocher

[edit]

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

I need something like a stream in which there is processing and is ready for keyboard input. Another thread is simply to control the network and pass on the received text to the processing thread.

+7
source share
4 answers

Perhaps you really need a queue lock. When you create a thread, you pass the lock queue internally, and the thread should continue to check if there is any item in the queue. Outside a thread, you can queue items while the thread is "running." Blocking a queue can prevent a thread from exiting if not done.

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

}

+10
source

The β€œother stream” will have its own life, so you will not be able to communicate with it / pass parameters if it does not actively read what you give it.

A stream with which you can communicate with it usually reads data from some buffer queue.

Take a look at ArrayBlockingQueue , and read on the Consumer-Producer template.

+4
source
 public class T1 implements Runnable { //parameter of thread T1 public static AtomicBoolean flag = new AtomicBoolean(); @Override public void run() { } } public class T2 implements Runnable { @Override public void run() { //parameter to an already running thread T1.flag.set(true); } } 
+2
source

How about this way:

  class TestRun implements Runnable { private int testInt = -1; public void setInt(int i) { this.testInt = i; } @Override public void run() { while (!isFinishing()) { System.out.println("Working thread, int : " + testInt); try { Thread.sleep(2500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } 

.....

  TestRun first = new TestRun(); TestRun second = new TestRun(); (new Thread(first)).start(); (new Thread(second)).start(); try { Thread.sleep(5000); } catch (InterruptedException e) { } first.setInt(101); second.setInt(102); 
0
source

All Articles