无需等待即可调用函数

嗨,我想知道是否有一种方法可以调用函数/方法(最好是在Python或Java中)并继续执行而无需等待它。

例:

def a(): b() #call a function, b() return "something" def b(): #something that takes a really long time 

在新线程中运行它。 在这里了解java中的multithreading和pythonmultithreading

Java示例:

错误的方式……通过inheritanceThread

 new Thread() { public void run() { YourFunction();//Call your function } }.start(); 

正确的方法……通过提供Runnable实例

 Runnable myrunnable = new Runnable() { public void run() { YourFunction();//Call your function } } new Thread(myrunnable).start();//Call it when you need to run the function 

正如其他答案中所提到的,从Python中你可以将函数放在一个新线程中(不是那么好,因为CPython中的线程不会让你获得太多),或者在另一个使用多处理的进程中 –

 from multiprocessing import Process def b(): # long process def a(): p = Process(target=b) p.start() ... a() 

(正如monkut的答案所示)。

但是Python的装饰器允许人们在地毯下隐藏样板,以一种在调用时,你“看到”正常函数调用的方式。 在下面的例子中,我创建了“并行”装饰器 – 只需将它放在任何函数之前,它将在调用时在一个单独的进程中自动运行:

 from multiprocessing import Process from functools import partial from time import sleep def parallel(func): def parallel_func(*args, **kw): p = Process(target=func, args=args, kwargs=kw) p.start() return parallel_func @parallel def timed_print(x=0): for y in range(x, x + 10): print y sleep(0.2) def example(): timed_print(100) sleep(0.1) timed_print(200) for z in range(10): print z sleep(0.2) if __name__ == "__main__": example() 

运行此代码段时,会得到:

 [gwidion@caylus Documents]$ python parallel.py 100 0 200 101 1 201 102 2 202 103 3 203 104 4 204 105 5 205 106 6 206 107 7 207 108 8 208 109 9 209 [gwidion@caylus Documents]$ 

在Java中,有一个标准的习惯用法:创建一个线程并运行它:

 new Thread() { @Override public void run() { callMyFunction(); } }.start(); 

或者您可以创建一个Runnable并将其传递给线程:

 Runnable caller = new Runnable() { @Override public void run() { callMyFunction(); } } new Thread(caller).start(); 

在python中使用多处理 :

 from multiprocessing import Process def b(): # long process p = Process(target=b) p.start() 

您最好从ExecutorService开始,而不是直接使用原始线程。 它提供了池化,完成检测,还有一些子类也有一些调度。 例如:

 ... // Create a simple instance with a single thread in the pool ExecutorService executor = Executors.newFixedThreadPool(1); ... Future future = executor.submit(new Callable() { @Override public Integer call() { return YourFunction(); } }); ... // To wait for YourFunction() to finish, and get the result: Integer result = future.get(); 

您可以根据需要向ExecutorService提交尽可能多的异步任务; 它们将并行执行,或者按顺序执行,具体取决于您选择的实现,支持线程池中的线程数等。

只需在新线程中调用该函数…