From Delphi to Java: tricks in thread execution

In the two comic viewers, portions of the application retrieves images from the web in the background, using a thread. While coding up a solution, I remembered that thread control is problematic, and utilizing my Delphi experience, I coded the terminate and isTerminated methods.

Combining Delphi experience with Sun's recommendation, the two new methods set, or returns the value of a volatile boolean. In the thread execution, the Run method calls either isTerminated method, or checks the mTerminated boolean and continues execution if it's false.

mThread = new StoppableThread() {
   public void run() {
       do {
// work
       } while (!mTerminated));

Since threads works with Runnables, when I coded up the terminate method, I added a check to see if the thread has a Runnable instance associated with it, and if so, calls it's terminate method as well.

    public void terminate() {
        if (mRunnable instanceof StoppableRunnable)
            ((StoppableRunnable) mRunnable).terminate();
        mTerminated = true;


Published Tue, 26 May 2009 @ 5:30 AM by chuacw
Related articles: ,