2

我正在研究java中的多线程并创建了1个线程,代码如下:

class SampleThread extends Thread
    {
        int time;
        String name;
        boolean autocall;
        public SampleThread(int time, String name)
        {
            this.time = time;
            this.name = name;
        }

          public void run()
          { 
              try{
                  time = time +1;
                  updateView(time, name);
                  //sleep(3000);
              }catch(Exception e)
              {
                  e.printStackTrace();
              }
            //this.stop();
          }     
    }

现在我想每 3 秒运行一次这个线程如何实现这个?

4

2 回答 2

5

我建议不要这样做。看看包中的类(好吧,不是那么新)java.util.concurrent,尤其是ScheduledThreadPoolExecutor

于 2012-10-22T10:30:50.567 回答
1

将 Java.util.Concurrent 用于新实现。如果您使用的是 JDK 1.4 或更低版本,请使用以下方法。

boolean isRunning = true;
public void run() {
        do {
           try {
                System.out.println("do what you want to do it here");
                Thread.sleep(3000l);
            } catch ( InterruptedException ie) {
               ie.printStackTrace();
           } catch (RunTimeException rte) {
               isRunning  = false; // terminate here if you dont expect a run time exception... 
           }
        } while ( isRunning );
    }
于 2012-10-22T11:09:33.877 回答