使用ThreadPoolExecutor时出错

时间:2016-02-28 08:18:08

标签: java executorservice threadpoolexecutor

我有以下Job,我希望ThreadPoolExecutor运行。我想打印每个作业的开始时间和结束时间。开始时间是打印但结束时间不打印。我不知道我做错了什么,请帮忙!

import java.util.concurrent.TimeUnit;  

public class Job  implements Runnable {
private long startTime,endTime,delay;
int id;

public Job(long delay) {
    this.delay=delay;

  }
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}

public long getstartTime() {
    return startTime;
}
public void setstartTime(long startTime) {
    this.startTime = startTime;
}
public long getendTime() {
    return endTime;
}
public void setendTime(long endTime) {
    this.endTime = endTime;
}

      @Override
public void run() {

     setstartTime(System.nanoTime());

       try{
           TimeUnit.MILLISECONDS.sleep(delay);
           }catch(InterruptedException e){
            }
    setendTime(System.nanoTime());
     }


    }

以下是主要课程

import java.util.Vector;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class OracleExecutorService {
    ThreadPoolExecutor executor; //= (ThreadPoolExecutor) Executors.newCachedThreadPool();
    Vector vector=new Vector();

    public OracleExecutorService() {
        super();
        this.executor= (ThreadPoolExecutor) Executors.newCachedThreadPool();
        runJobs();
        displayResults();
        this.executor.shutdown();
    }

    private void displayResults() {
        // TODO Auto-generated method stub
        for(int i=0;i<vector.size();i++){
            Job job=(Job)vector.get(i); 
            System.out.println("Job id="+job.getId()+" start time="+job.getstartTime());
            System.out.println("Job id="+job.getId()+" end time="+job.getendTime());            
        }
    }

    private void runJobs() {
        // TODO Auto-generated method stub
        int count;
        for (int i = 0; i <= 5; i++) 
        {
            Job job=new Job(100); //100milliseconds
            count=i+1;
            job.setId(count);
            vector.add(job);
            executor.execute(job);
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new OracleExecutorService();


    }

}

OutPut如下

工作ID = 1开始时间= 935938224433767

工作ID = 1结束时间= 0

工作ID = 2开始时间= 935938224477583

工作ID = 2结束时间= 0

工作ID = 3开始时间= 935938224648899

工作ID = 3结束时间= 0

工作ID = 4开始时间= 935938224696268

工作ID = 4结束时间= 0

工作ID = 5开始时间= 935938224749952

工作ID = 5结束时间= 0

工作ID = 6开始时间= 935938224796532

工作ID = 6结束时间= 0

1 个答案:

答案 0 :(得分:2)

没有错误。

基本上在设置endTime之前,或者甚至在作业完成之前,你调用displayResults。

     runJobs();
    Thread.sleep(200);// wait for the job to finish - would make the end time is set and display
    displayResults(); 

试试这个。你会知道会发生什么。

   setendTime(System.nanoTime());
   System.out.println("I am done:" + System.nanoTime());