有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java调度一个小程序,从ScheduledExecutorService开始

我有一个简单的时钟小程序,我希望能够通过ScheduledExecutorService控制它,但是我有点不确定如何使线程从ScheduledExecutorService开始。调度命令

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class UpdateApplet extends java.applet.Applet implements Runnable
{

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    Thread thread;
    boolean running;
    int updateInterval = 1000;

    final Runnable clock = new Runnable(){//Can't take credit for this, thnx KH
        public void run(){
            while(true)
                repaint();
        }
    };

    public void run( ){
        scheduler.schedule(clock, 10, TimeUnit.SECONDS);//edited this here
    }

    public void start( ){
        System.out.println("starting...");
        if ( !running) //naive approach
        {
            running = true;
            thread = new Thread(this);
            thread.start( );
        }
    }

    public void stop( ){
        System.out.println("stopping...");
        thread.interrupt( );
        running = false;
    }
}

public class Clock extends UpdateApplet{

    public void paint(java.awt.Graphics g){
        g.drawString(new java.util.Date( ).toString( ), 10, 25);
    }

}

我相信这是一个简单的解决办法,但我就是看不到。任何帮助都将不胜感激


共 (1) 个答案

  1. # 1 楼答案

    您需要使用scheduleAtFixedRate。同样,您不需要在run方法中使用线程

    class UpdateApplet() implements Runnable {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        volatile boolean running;
        int updateInterval = 1000;
    
        public void start() {
           scheduler.schedule(this, updateInterval, updateInterval, TimeUnit.MILLISECONDS);
        }
    
        public void run() {
             if(!running) {
                 scheduler.shutdown();
             }
             else {
                  repaint();
             }
        }
    }