How to pass an argument to a stream

Suppose I would like to pass the following variable

String foo = "hello world"; 

as an argument for the next thread

 new Thread(new Runnable() { @Override public void run() { // SOME CODE HERE REQUIRES VARIABLE } }).start(); 

Can someone explain how to do this.

Thanks.

+4
source share
5 answers

Local variables declared as final will be visible in the stream:

 void doSomething(final String foo) { new Thread(new Runnable() { @Override public void run() { // SOME CODE HERE REQUIRES VARIABLE System.out.println(foo); } }).start(); } 
+3
source

Subclass Subject:

 public class MyThread extends Thread { private String arg; public MyThread(String arg) { this.arg = arg; } @Override public void run() { // Use your variable } } 
+4
source

Can someone explain how to do this.

So your problem has more solutions, but from the very beginning. I suggest you create your own subclass of Thread and pass the parameter through the constructor .

 public class MyThread extends Thread { public MyThread(String value) { } } 

Or you can also use the Runnable interface.

 public class MyThread implements Runnable { ... } 

Update:

Or as @erickson pointed out that you can wrap your code in the body of the method, but as an argument to the method you must pass a final variable, because you cannot but refer to a non-final variable inside the inner class defined by another method.

+3
source

You cannot pass an argument using anonymous classes in Java. What you can do is create a separate class and pass it as an instance variable

0
source
 String foo = "hello world"; final String parameter = foo; new Thread(new Runnable() { @Override public void run() { //Use parameter } }).start(); 
0
source

All Articles