如何实现每30秒就执行一段程序?

peppi 2002-12-26 02:03:00
假设我有一方法:
public void a()
{
System.out.println("testing");
}

我有多少种方法可以让它每隔30秒就执行一次?永不停止!
请重点说明如何利用线程来实现,谢谢!最好有代码.
...全文
96 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
deniswang 2002-12-26
  • 打赏
  • 举报
回复
线程无法保证时间准确,最好用Timer
松耦合紧内聚 2002-12-26
  • 打赏
  • 举报
回复
觉得beyond_xiruo(希偌)的方法正规!标准计时器的使用。
线程睡30秒不是准确时间.
SnowOct 2002-12-26
  • 打赏
  • 举报
回复
支持一下
jackal81 2002-12-26
  • 打赏
  • 举报
回复
同意 wang_zheng_wz(流星雨) 的说法
希偌 2002-12-26
  • 打赏
  • 举报
回复
interface TimerListener{
public void processEvent();
}

public Class Clock implements TimerListener{
Clock(){
Timer t=new Timer(this); //向Timer类登记
}
public void processEvent(){
//你的事件处理的代码
}
}

class Timer extends Thread {

private TimerListener tl;
Timer(TimerListener tl){
this.tl=tl;
}
public void run(){
while(true){
sleep(1000);
tl.processEvent();
}
}
}
wang_zheng_wz 2002-12-26
  • 打赏
  • 举报
回复
用线程:
import java.io.*;


class AThread extends Thread {
private boolean stop = false;

public void terminate() {
stop = true;
}

public AThread() {
this.start();
}

public void run() {
while (!stop) {
try {
sleep(30 * 1000);
} catch (InterruptedException e) {
System.err.println("Interrupted");
}
System.out.println("testing");
}
}
}


public class Test {
public static void main(String[] args) throws IOException {
AThread a = new AThread();
System.out.println("Press enter");
System.in.read();
a.terminate();
}
}

不用线程:
用java.util.Timer
deniswang 2002-12-26
  • 打赏
  • 举报
回复
用timer
希偌 2002-12-26
  • 打赏
  • 举报
回复
用线程
public void a() throws Exception
{
while(true) {
System.out.println("testing");
Thread.sleep(30000);
}
}

62,635

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧