×

Discussion Board

Results 1 to 6 of 6

Thread: About Thread

  1. #1
    Registered User
    Join Date
    Nov 2003
    Posts
    33

    About Thread

    Hi,
    Could anybody tell me how to terminate the current thread?

    thanks

    linbo

  2. #2
    Super Contributor
    Join Date
    Mar 2003
    Location
    Israel
    Posts
    2,280
    The moment the run() method of the Thread is finished the thread will be terminated.

    shmoove

  3. #3
    Registered User
    Join Date
    Nov 2003
    Posts
    33

    Thanks,but.....

    Hi,
    thank for your reply.
    What I want is to terminate the thread if I press a cancel button
    because this thread might take very long time ( used for searching something)

    thanks again

    linbo

  4. #4
    Super Contributor
    Join Date
    Mar 2003
    Location
    Israel
    Posts
    2,280
    The only thing you can do is set a variable when you want to cancel, and test this variables in several places in the run() method:
    Code:
    boolean cancel;
    // ....
    public void run() {
      cancel = false;
      doSomething();
      if (cancel) return;
      while (somethingOrOther) {
        doSomethingElse();
        if (cancel) return;
      }
      for (int i = somenumber; i >= 0; i--) {
        doSomethingAgain();
        if (cancel) return;
      }
      doAnotherThing();
      if (cancel) return;
      doOneMoreThing();
      return;
    }
    // ....
    public void commandAction(Command c, Displayable d) {
      if (c == cancelCommand) {
        cancel = true;
      }
    }
    If you want to cancel in the middle of one of the doSomething() methods then you'll have to check for cancel in them too. If it's a system method (part of the MIDP API), then you're screwed.

    shmoove

  5. #5
    Registered User
    Join Date
    Nov 2003
    Posts
    33

    Thanks a lot

    Hi shmoove,

    Thank you very much

    linbo

  6. #6
    Registered User
    Join Date
    Mar 2003
    Posts
    33
    Don't forget to declare the cancel boolean as 'volatile', or synchronize all access to it. Otherwise, setting it to true might not be visible to the Thread you want to cancel, depending on the JVM used.

    -- Niek

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
×