2012-03-29 46 views
1

我正在開發基於Java EE的應用程序,其中需要使用itext API的PDF報告。 基本上我的要求是,如果報告生成需要超過1分鐘,然後停止它。如何在1分鐘內完成任務,如果任務未完成則將其丟棄

因此,對於這個我這樣

Thread t = new Thread(myPojoclass); 

long startTime = System.currentTimeMillis(); 
long endTime = startTime + 60000; 

t.start(); 

while (System.currentTimeMillis() < endTime) 
{ 

} 

t.interrupt(); // Tell the thread to stop 

而且裏面實現這個業務需求我myPojoclass如上面提到的,這是實現Runnable接口和它的run方法裏面它是由連接到的主題數據庫 並獲得結果並將其提供給ArrayList

請讓我知道這是否正確?

+0

這些帖子已回答您的問題:http://stackoverflow.com/q/2758612/948268和http://stackoverflow.com/q/1247390/948268 – 2012-03-29 09:36:45

回答

0

可以使用執行服務

ScheduledExecutorService executor = Executors.newScheduledThreadPool(2); 
final Future handler = executor.submit(new Callable(){ ... }); 
executor.schedule(new Runnable(){ 
    public void run(){ 
     handler.cancel(); 
    }  
}, 60000, TimeUnit.MILLISECONDS); 

詳情 ExecutorService that interrupts tasks after a timeout

+3

你還應該提到你從這篇文章中複製它http://stackoverflow.com/q/2758612/948268 – 2012-03-29 09:36:12

2

有一個很好的解決方案here。由於您的線程正在連接到數據庫,我強烈建議(如果您尚未完成)捕獲InterruptException異常並在其塊內關閉連接並在必要時進行回滾。