2011-11-04 70 views
4

的问题是混乱的,但多数民众赞成什么,我想做的事:调用方法

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();”它将由主线程处理。

+1

是的,我已经从它运行.. –

回答

4

Runnable的想法是它是一个整合的代码片段,可以在其选择的任何上下文(在这种情况下,一个线程)内由其他内容执行。第二个线程在启动时将调用run()方法,因此您可能希望在MyClass.run()方法中调用foo()。您不能从主线程中任意决定第二个线程现在要放弃run()方法中的任何操作,并开始处理foo()

+0

“你不能擅自决定,从主线程,第二线程现在要放弃不管它是在run()方法,并开始做致力于foo()。“ 当你说“你不能任意决定”时,我不知道你的意思,但是它可以在main方法中运行foo,而在其run()方法中运行一些可运行的对象无限循环。那么,当主方法调用'run()'时发生了什么?它是从主进程的线程运行吗? –

+1

@DaleMarkowitz如果'main'方法直接调用'run',那么'run'将在'main'正好执行的任何线程中执行.OP想要控制一个不同的线程并将其执行转移到一个不可能直接实现的功能(即任意决定)。 –

3

你不能调用一个线程,你只能发信号。如果你想让foo()被执行,你必须发信号通知run()让它执行foo()。

+0

如果foo()返回,例如,对另一个对象的引用,我将其称为它在示例中完成的方式,那么foo()返回的值是什么? –

1

改变你的代码如下:

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

我会修改你的类包含一个Executor,再有它的方法要求执行运行任务。通过将执行器传递给MyClass的构造函数,主要控制任务如何执行。

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"); 
      } 
     }); 
    } 
}