2016-02-28 56 views
2

我有以下Job,我想讓ThreadPoolExecutor運行。我想打印每個作業的開始時間和結束時間。開始時間正在打印,但結束時間不打印。我不知道我在做什麼錯,請幫忙!使用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(); 


    } 

} 

輸出如下

作業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

回答

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());