簡體   English   中英

使用 ScheduledExecutorService 調度 Applet 啟動

[英]Scheduling an Applet start with ScheduledExecutorService

我有一個簡單的時鍾小程序,我希望能夠通過 ScheduledExecutorService 進行控制,但是我有點不確定如何使用 ScheduledExecutorService.schedule 命令啟動線程。

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);
    }

}

我確信它是一個簡單的修復,但我只是沒有看到它。 任何幫助將不勝感激。

您需要使用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();
         }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM