java中一个线程如何执行多次
1个回答
展开全部
在线程里使用循环,然后睡眠一段时间再执行。 或者使用 java.util.Timer; java.util.TimerTask; 来设置定时执行任务。
仅供参考
package com.kidd.test.zhidao;
/**
* Hello world!
*
*/
public class Main {
public static void main(String[] args) {
Seed seed = new Seed();
TestRunnable testRunnable = new TestRunnable(seed);
Thread thread = new Thread(testRunnable);
thread.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
seed.setEnd(true);
}
}
class TestRunnable implements Runnable {
private Seed seed;
public TestRunnable(Seed seed) {
super();
this.seed = seed;
}
public Seed getSeed() {
return seed;
}
@Override
public void run() {
while (!seed.isEnd()) {
System.out.println("线程正在执行");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Seed {
private boolean end;
public boolean isEnd() {
return end;
}
public void setEnd(boolean end) {
this.end = end;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询