执行器服务:SingleThreadExecutor不触发可运行对象

时间:2019-04-24 18:09:38

标签: java concurrency executorservice

我正在尝试使用Java并发包的ExecutorService SingleThreadExecutor执行可运行对象。当我在新的Runnable对象上调用execute命令时,它只需跳过它即可。即未调用run()方法。

我已经使用调试器逐步完成了代码行,可以看到我的SingleThreadExecutor已创建并且我的Runnable已初始化。

public class RunnableDemo {

    public ExecutorService executor;

    public RunnableDemo () {
        this.executor = Executors.newSingleThreadExecutor();
    }

    public void start(){
       executor.execute(new MyRunnable("Hello World"));
    }

   public static void main(String[] args){
        RunnableDemo app = new RunnableDemo();
        app.start();
    }
}

public class MyRunnable implements Runnable {
   private String strToPrint;

   public MyRunnable(String parameter) {
       this.strToPrint = parameter;
   }

   public void run() {
      System.out.println(strToPrint);
   }
}

也许是不言自明的,但是在这种情况下,我希望看到“ Hello World”印在屏幕上。但是,似乎在创建runnable之后不会调用execute / run方法。

1 个答案:

答案 0 :(得分:-1)

您的程序在执行者开始执行任务之前终止。

您必须等待执行者完成以下操作:

public class RunnableDemo {

public ExecutorService executor;

public RunnableDemo () {
    this.executor = Executors.newSingleThreadExecutor();
}

public void start(){
   executor.execute(new MyRunnable("Hello World"));
}

public void awaitTermination(){
  try {
        service.awaitTermination(10, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public static void main(String[] args){
    RunnableDemo app = new RunnableDemo();
    app.start();
    app.awaitTermination();
}
}

public class MyRunnable implements Runnable {
private String strToPrint;

public MyRunnable(String parameter) {
   this.strToPrint = parameter;
}

public void run() {
  System.out.println(strToPrint);
}
}