有什么方法不等待执行代码块或方法?

Gna*_*nam 5 java concurrency jakarta-mail

为了不等待代码块/方法在Java中完成执行,有哪些正确的方法/实践/实现/策略(或者我们称之为)?

假设以下方法:

private void myMethod()
{
     // Some lines of code here
     .....
     .....
     .....

     anotherMethod(); // or this could be a code block

     // Again some lines of code here
     .....
     .....
     .....
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我希望myMethod()不要等待代码完成执行anotherMethod().我还可以在此确保后续的代码行不依赖于在其中执行的任何内容anotherMethod().

Jig*_*shi 7

如果没有依赖关系,您可以在另一个Thread中启动它.

new Thread(new Runnable(){

      public void run(){
           anotherMethod();
      }  

}).start();
Run Code Online (Sandbox Code Playgroud)


Boz*_*zho 7

使用

Executor executor = Executors.newSingleThreadExecutor();
executor.execute(new Runnable() {
    @Override
    public void run() {
       anotherMethod();
    }
});
// this is called automatically when the object is gc-ed, 
// but you should not rely on this, hence the explicit call
executor.shutdown();
Run Code Online (Sandbox Code Playgroud)

引用Effective Java:

您不仅应该避免编写自己的工作队列,而且通常应该避免直接使用线程.关键的抽象不再是Thread,它既是工作单元又是执行它的机制.现在工作单位和机制是分开的.关键抽象是工作单元,称为任务.有两种任务:Runnable及其近亲Callable(类似于Runnable,除了它返回一个值).执行任务的一般机制是执行者服务.如果您考虑任务并让执行程序服务为您执行它们,那么您在选择适当的执行策略方面会获得很大的灵活性.本质上,Executor Framework执行Collections Framework为聚合所做的工作.

请注意,您最好只创建一次执行程序,将其存储在实例字段中并重复使用(然后将其关闭)

如果您在JavaEE的6或弹簧运行时,可以标注您anotherMethod()@Asynchronous和容器将开始一个新的线程为您服务.

  • 代码不明确和误导 - 线程池很昂贵,不应该只在方法级别使用一次.您也忘记了处置线程池. (2认同)