2012-03-12 108 views
1

我有這樣的C#代碼:相當於Java的C#Action.BeginInvoke

Action action = MyFunction; 
action.BeginInvoke(action.EndInvoke, action); 

其中,從我所知道的,只是運行MyFunction的異步方式。你可以在Java中做同樣的事情嗎?

回答

5

這是你如何可以運行在自己的線程Java中的作用:

new Thread(new Runnable() { 

    @Override 
    public void run() { 
     aFunctionThatRunsAsynchronously(); 
    } 
}).start(); 

有跡象表明,給你的東西是如何運行的,例如Executors更多的控制提供其他高級框架,它可以例如用於schedule events

+0

'BeginInvoke'將使用線程池,有沒有在Java中這樣的概念? - 對不起,我應該花一秒鐘來關注你的「執行者」鏈接!謝謝 – weston 2012-03-12 14:50:47

+0

是的:http://docs.oracle.com/javase/tutorial/essential/concurrency/pools.html – assylias 2012-03-12 14:51:43

+0

當我嘗試這個時,我得到錯誤「類型new Runnable(){}的方法run()必須覆蓋超類方法「。 – adam0101 2012-03-12 14:51:47

1

這與Asynchronous Event Dispatch in Java有些相關。基本上,您可以將您希望運行的方法構造爲實現Callable或Runnable的類。 Java不能像C#那樣將「方法組」引用爲變量或參數,因此即使Java中的事件處理程序也是實現定義偵聽器的接口的類。

嘗試是這樣的:從Oracle Java文檔

Executor scheduler = Executors.newSingleThreadExecutor(); 

//You'd have to change MyFunction to be a class implementing Callable or Runnable 
scheduler.submit(MyFunction); 

更多閱讀:

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Executors.html

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ScheduledExecutorService.html

2

本身的的ExecutorService提供了我能想到的最接近的一次。這裏是你如何使用ExecutorService的運行方法異步再後來得到返回值:

ExecutorService executor = Executors.newFixedThreadPool(NTHREDS); 
Future<String> future = executor.submit(new Callable<String>() { 
    return getSomeLongRunningSomethingHere(); 
}); 
//... do other stuff here 
String rtnValue = future.get(); //get blocks until the original finishes running 
System.out.println(rtnValue);