Calling an executable instance method outside of runnable that is runnable thread

The question is confusing, but here is what I want to do:

public class Main { MyClass instance = new MyClass(); Thread secondThread = new Thread(instance); public static void main() { secondThread.start(); //here i want to call foo(), but be processed by secondThread thread(not the Main thread) } } public class MyClass implements Runnable { @Override public void run() { } public void foo() { System.out.println("foo"); } } 

If I use "instance.foo ();" it will be processed by the main thread.

+4
source share
4 answers

The idea of Runnable is that it is a consolidated piece of code that can be executed by something else inside any context that it selects (in this case, a thread). The second thread will call the run() method when it starts, so you can have a call to foo() in your MyClass.run() method. You cannot arbitrarily decide, from the main thread, that the second thread is now going to abandon everything that it did in the run() method, and start working with foo() .

+4
source

You cannot trigger a flow, you can only signal it. If you want foo () to be executed, you must signal run () to ask it to execute foo ().

+3
source

change your code as below:

 public class Main { Object signal = new Object(); MyClass instance = new MyClass(); Thread secondThread = new Thread(instance); public static void main() { instance.setSignal(signal); secondThread.start(); synchronize(signal) { try{ signal.notify();**//here will notify the secondThread to invoke the foo()** } catch(InterrupedException e) { e.printStackTrace(); } } } public class MyClass implements Runnable { Object signal; public setSignal(Object sig) { signal = sig; } @Override public void run() { synchronize(signal) { try{ signal.wait(); } catch(InterrupedException e) { e.printStackTrace(); } } this.foo(); } public void foo() { System.out.println("foo"); } } 
+1
source

I would modify your class to contain Executor, and then ask it to complete the task to complete this task. Passing the executor to the MyClass constructor, the main control element for the execution of tasks.

 public class Main { Executor runner = Executors.newSingleThreadExecutor(); MyClass instance = new MyClass(runner); public static void main() { instance.foo(); // cleanup executor } } public class MyClass { private final Executor runner; public MyClass(Executor runner) { this.runner = runner; } public void foo() { runner.execute(new Runnable() { public void run() { System.out.println("foo"); } }); } } 
+1
source

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


All Articles