多线程执行器服务-java

时间:2015-11-20 18:05:53

标签: java multithreading

我有执行器服务执行特定线程。执行该线程后,它会在一段时间后进入休眠状态。但是在这个时候,我希望另一个线程开始执行相同的操作并继续这样做。我使用执行程序服务尝试了以下程序,但它的行为类似于顺序处理。请建议我在java中进行哪些更改或任何其他类来实现上述方案。

class WorkerThread implements Runnable {

    private String command;

    public WorkerThread(String s){
        this.command=s;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+" Start. Command = "+command);
        processCommand();
        System.out.println(Thread.currentThread().getName()+" End.");
    }

    private void processCommand() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString(){
        return this.command;
    }
}


  class ThreadPool {
      public static int times=0;
 public static ExecutorService executor = Executors.newFixedThreadPool(1);
    public static void main(String[] args) 
    {

       int i=0;
        while(i<2)
        {
        Runnable worker = new WorkerThread("proud");
         executor.execute(worker);
         times++;
         //executor.shutdown();
       i++;
        }
       executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println("Finished all threads");
    }

} 

0 个答案:

没有答案