Question about Runnable Interface in java?

One way to implement a stream is as follows:

Runnable r1 = new Runnable() { public void run() { // my code here } }; Thread thread1 = new Thread(r1); thread1.start(); 

Now, if I stick to this simple method, you still need to pass the value inside the execution unit from outside this thread. For example, my code inside run contains logic that requires a stream of output from the process that will be used in the call.

How can I pass this process thread object to this run block.

I know that there are other methods, such as a runnable or extension thread implementation, but can you tell me how to do this using the above method.

+4
source share
3 answers

You can use the local final variable:

 final OutputStream stream = /* code that creates/obtains an OutputStream */ Runnable r1 = new Runnable() { public void run() { // code that uses stream here } }; Thread thread1 = new Thread(r1); thread1.start(); 

final variables are visible to anonymous inner classes such as your Runnable above.

If your Runnable gets complicated enough, you should consider turning it into a named class. At this point, constructor arguments are usually the best mechanism for passing parameters.

+5
source

This answer assumes that when you start the stream, you do not have an OutputStream , but it will be received later. If you already have a reference to the stream object, you should use the Lawrence example instead.


You can use some wrapper class, for example:

 // This is a very simplified example; use getters and setters instead. class OutputStreamWrapper { public OutputStream outputStream; } 

Then you can do this:

 final OutputStreamWrapper wrapper = new OutputStreamWrapper(); Runnable r1 = new Runnable() { public void run() { // use wrapper.outputStream in here when appropriate } }; Thread thread1 = new Thread(r1); thread1.start(); 

Then you pass the object referenced by the wrapper variable to some other method or class, which in turn set the OutputStream property to pass the stream to the stream code.

Note that this is a kind of hack; implementing Runnable in another class and providing it with such a field would be preferable.

+1
source

Yes it is possible. From inside the run method, you can access all the variables in the environment method that has the final qualifier.

 public void demo() { final int accessible = 123; int notAccessible = 456; new Thread(new Runnable() { public void run() { System.out.println(accessible); } }.start()); } 
0
source

Source: https://habr.com/ru/post/1333438/


All Articles