没有通用的方法只是将一些代码发送到另一个正在运行的线程中,然后说“嘿,您这样做”。您需要将主线程置于一种具有接收工作并等待工作完成的机制的状态。
这是设置主线程以等待从其他线程接收工作并在到达时运行它的简单示例。显然,您可能想添加一种方法来实际结束程序,等等……!
public static final BlockingQueue<Runnable> queue = new linkedBlockingQueue<Runnable>();public static void main(String[] args) throws Exception { new Thread(new Runnable(){ @Override public void run() { final int result; result = 2+3; queue.add(new Runnable(){ @Override public void run() { System.out.println(result); } }); } }).start(); while(true) { queue.take().run(); }}


