當前位置:編程學習大全網 - 編程語言 - 在JAVA中如何實現長時間任務

在JAVA中如何實現長時間任務

壹、問題背景    在應用程序中我們經常需要壹個類去完成像數據處理、監聽事件或檢查另壹個類的活動等任務。為了達到這個目標,我們可能使用帶有壹套鎖和消息通知的線程。JAVA 線程API已經很好的文檔化,但為了使線程能夠正確而高效地運行,程序員仍然需要豐富的編程經驗並編寫大量的代碼。通過應用本篇文章中討論的框架,程序員能夠避免忍受煎熬寫大量的代碼,快速創建健壯的應用程序。    二、長時間運行任務的程序框架  Framework for long-running tasks    The primary thing about a long-lived task is that it should somehow be kept running during the application lifetime. The right way to accomplish this is to provide a thread of execution for a particular task. You create a task as a thread or as an implementation of the java.lang.Runnable interface. If you implement Runnable, you can gain better object-oriented design and avoid the single-inheritance problems. You can also more efficiently manipulate with Runnable instances, for example, using a thread pool that usually needs a Runnable instance, not a thread, to run.    關於長時間運行的任務的主要事情是如何在應用程序的生命期使它壹直保持運行。實現的恰當方法是提供壹個線程來執行這個特定的任務。我們可以通過繼承Thread類或實現java.lang.Runnable接口來達到該目標。如果采用實現Runnable接口的方式,就可以能夠獲得更好的面向對象的設計,同時可以避免JAVA中的單繼承問題。另外,我們也能更有效的處理Runnable實例(例如使用線程池通常需要壹個Runnable實例而不是線程來運行)。    The essence of the framework is the abstract class Worker ( Listing A), which implements the Runnable interface and provides the helper methods for efficient task handling. Some of the methods are fully implemented, like the run() method, but some are abstract and have to be filled by you. If you want to create a long-running class, you need only to extend the Worker class and implement several abstract methods. Let’s look at these methods in more detail.    框架的基礎是壹個叫Worker的抽象類,它實現了Runnable接口,並提供了有效處理任務的好方法。這些方法有些已經被實現,如run()方法,但有些是抽象方法,開發人員必須自己來實現。如果要創建壹個長時間運行的類,妳只需要繼承Worker類並實現幾個抽象方法。讓我們看看這些方法的細節。    The run() method of the Worker class is designed to continuously execute the work() method until it is stopped. The work() method can be responsible for data processing, reaction to some event, file reading or writing, SQL execution, etc. It can throw an exception, so it is a good practice to propagate it and let the run() method handle it.    Worker 類的run()方法被設計成只要不停止運行就持續的執行work()方法。work()方法可以負責數據處理、事件響應、文件讀寫、,執行SQL命令等操作。這樣work()方法能夠拋出異常,並將異常傳給run(),然後由run()方法來處理這些異常。    The run() method has two levels of try-catch clause: outside and inside the while-loop. The first try-catch clause is meant to catch all nonprogrammed exceptions and guarantee that the run() method never exits. The second clause will catch any kind of exceptions belonging to business logic and behave accordingly. If some waiting operation takes place in the work() method (e.g., waiting on an InputStream or a Socket), it is advisable to propagate an InterruptedException. The thing to keep in mind is that the work() method does not need to have any while-loop to keep it going as long as an application runs. The Worker does this for you.    run()方法有內外兩層try-catch語句:壹層處於while-loop循環外,壹層在while-loop循環內。前壹個try-catch用於捕獲非編程異常以確保run()方法不退出。後壹個try-catch語句捕獲關於業務邏輯和相應行為的各種異常。如果在work()方法中發生了壹些等待操作(例如等待壹個輸入流或壹個Socket),拋出壹個InterruptedException的方法是可取的。要記住的是只要應用程序在運行,work()方法不需要任何while-loop循環去維持它運行,這壹切由Worker代辦了。    When the run() method starts, it calls the prepareWorker() which is designed to prepare all resources needed for a long-running task (Listing A). In this method call, you can, for example, establish a database connection or open a file that will be used further. It is especially good to place here some blocking operations like opening a socket, because they will be done in a separate thread and thus will not block the main thread of execution.    run()開始時,調用prepareWorker()方法來準備長時間運行任務需要的所有資源(參考程序清單A)。例如 ,在這個方法中可以打開壹個將要用到的數據庫連接或文件。尤其對於那些像建立壹個socket這樣的阻塞操作放在這兒是很好的。因為若讓它們在壹個獨立的線程中運行,則不會阻塞主線程的執行。    The opposite of the previous method is the releaseWorker() which is called when the run() method is about to exit (Listing A). Here, you can put the code to dispose of system resources used by this task or to perform other cleanup. This method is similar to java.lang.Object.finalize(), but it is explicitly called before a thread terminates.    與前面方法相反的是releaseWorker(),它在run()方法準備退出時被調用(參考程序清單A)。在該方法中妳可以編寫那些釋放系統資源或執行其它清除動作的代碼。該方法類似於java.lang.Object.finalize(),但它在線程中止時被顯式的調用。    三、框架中的錯誤處理機制  Handling errors in the framework    Another important method is the handleError(), which takes a java.lang.Throwable as a parameter. This method is called each time an error situation occurs within the run() method. It is up to you how to implement error handling. One way is to log errors and control task termination by calling halt() method (Listing A).    The isCondition() method is used to tell whether execution of the work() method can be started, thus allowing granular control over a task. It is useful in event-triggered frameworks when execution of the work() method is pending until some condition?for example, a buffer is not empty?is fulfilled. In Worker’s implementation, the condition is checked upon a lock notification and periodically with a time interval you specify in the setTimeout() method (Listing A). If you don’t need any waiting blocks in a task, just make the isCondition() method always return true.    isCondition()方法用於判斷work()方法是否能夠被執行。因此允許細粒度地控制任務。這在事件觸發的框架中非常有用。當work()方法的執行條件未滿足時,work方法將被掛起,直到條件完全滿足(例如,緩存區非空)。在Worker的實現中這個條件將按在方法setTimeout()中指定的時間周期地檢查壹個鎖通知。如果在任務中不需要任何等待阻塞,僅僅只要使isCondition()方法總是返回真值。    四、任務終止時機

  • 上一篇:福建新崛起的“黑馬”城市泉州市,有望躋身於新壹線城市嗎?
  • 下一篇:免費幫助編程
  • copyright 2024編程學習大全網