Results 1 to 2 of 2
  1. #1
    Join Date
    Apr 2004
    Location
    Amiens (FRANCE)
    Posts
    15

    Question Unanswered: why my thread run once on time ??

    i found on the internet this class to emulate a Timer.
    But when i was run it (by a action on a button), it is excecuted only one time.
    Why ??
    i want it to be executed in Loop.

    Code:
    class Timer extends Thread
    {
     private int _delay;
     private TimerListener _listener;
     public Timer(int delay, TimerListener listener) {
      _delay = delay;
      _listener = listener;
     }
     public void run() {
      try {
       sleep(_delay); }
      catch (Exception ex) { ex.printStackTrace();}
      _listener.executedMethod();
     }
    }
    
    interface TimerListener {
     public abstract void executedMethod();
    }
    
    // création du timer :
    Timer timer = new Timer(500, new TimerListener() {
     public void executedMethod() {
      System.out.println("coucou");
     }
    });
    // lancement
    timer.start();
    Ps : i'm sorry for my english language expression mistake, cause i 'm french

  2. #2
    Join Date
    Mar 2004
    Posts
    16

    Re: why my thread run once on time ??

    Originally posted by USA Mike
    i found on the internet this class to emulate a Timer.
    But when i was run it (by a action on a button), it is excecuted only one time.
    Why ??
    i want it to be executed in Loop.

    Code:
    class Timer extends Thread
    {
     private int _delay;
     private TimerListener _listener;
     public Timer(int delay, TimerListener listener) {
      _delay = delay;
      _listener = listener;
     }
     public void run() {
      try {
       sleep(_delay); }
      catch (Exception ex) { ex.printStackTrace();}
      _listener.executedMethod();
     }
    }
    
    interface TimerListener {
     public abstract void executedMethod();
    }
    
    // création du timer :
    Timer timer = new Timer(500, new TimerListener() {
     public void executedMethod() {
      System.out.println("coucou");
     }
    });
    // lancement
    timer.start();
    Because you didn't actually use any kind of loop...
    try to replace

    Code:
    public void run() {
      try {
       sleep(_delay); }
      catch (Exception ex) { ex.printStackTrace();}
      _listener.executedMethod();
     }
    with

    Code:
    public void run() {
     for (;;)
     {
       try {sleep(_delay); }
       catch (Exception ex) { ex.printStackTrace();}
       _listener.executedMethod();
     }
    }
    and you will have the loop you requested...

Posting Permissions

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