本文介绍了安排一个Applet下手ScheduledExecutorService的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的时钟小程序,我希望能够通过ScheduledExecutorService的控制,但我对如何使线程开始与ScheduledExecutorService.schedule命令有点不确定。
I have a simple Clock Applet that I would like to be able to control via the ScheduledExecutorService, however I'm a little unsure as to how to make the thread start with the ScheduledExecutorService.schedule command.
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);
}
}
我敢肯定它的一个简单的修复,但我没有看到它。任何帮助将大大AP preciated。
I'm sure its a simple fix, but I just don't see it. Any help will be greatly appreciated.
推荐答案
您需要使用 scheduleAtFixedRate 。同样,你也不需要使用运行方法中的一个线程,
You need to use scheduleAtFixedRate. As well, you don't need to use a thread within the run method,
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();
}
}
}
这篇关于安排一个Applet下手ScheduledExecutorService的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!