这个问题令人困惑,但这就是我想要做的:
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");
}
}如果我使用"instance.foo();“,它将由主线程处理。
发布于 2011-11-05 00:43:16
Runnable的思想是,它是一段合并的代码,可以由它选择的任何上下文(在本例中为线程)中的其他东西执行。第二个线程将在启动时调用run()方法,因此您可能希望在MyClass.run()方法中调用foo()。您不能从主线程任意决定第二个线程现在要放弃它在run()方法中所做的任何事情,而开始在foo()上工作。
发布于 2011-11-05 00:50:26
你不能调用一个线程,你只能给它发信号。如果您希望执行foo(),则必须向run()发出信号,要求它执行foo()。
发布于 2011-11-05 00:56:26
如下所示更改您的代码:
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");
}
}https://stackoverflow.com/questions/8012644
复制相似问题