The question is confusing, but thats 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.
The idea of a Runnable
is that it's a consolidated piece of code that can be executed by something else inside of whatever context it chooses (in this case, a thread). The second thread will call the run()
method when it starts, so you may want to have a call to foo()
within your MyClass.run()
method. You cannot arbitrarily decide, from the main thread, that the second thread is now going to abandon whatever it was doing in the run()
method and start working on foo()
.
You cannot call a thread, you can only signal it. If you want foo() to be executed, you have to signal run() to ask it to execute foo().
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");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With