我是java中的新手,有一个问题我需要面对它。如果我这样做:
//somecode
double number=0;
Timer timer = new Timer();
timer.schedule(new someFunction(),0,1);
我怎样才能做其他事情,只有在这个时间表完成后(经过一些互动后才会这样做)?
如果我试试这个:
//somecode
double number=0;
Timer timer = new Timer();
timer.schedule(new someFunction(),0,1);
number=1;
数字的变化将在任务结束之前发生。有办法解决这个问题吗?我写了一个功能代码来更好地揭示我的问题:
import java.util.Timer;
import java.util.TimerTask;
public class Main {
public static void main( String[ ] args ) {
class SomeTask extends TimerTask {
private double someVariable;
public SomeTask(double someVariable){
this.someVariable=someVariable;
}
public void run() {
while(this.someVariable<10){
this.someVariable++;
System.out.println(this.someVariable);
}
this.cancel();
}
}
boolean allTaskDone=false;
double someVariable=0;
Timer timer = new Timer();
timer.schedule(new SomeTask(someVariable),0,1000);
allTaskDone=true;
System.out.println(allTaskDone);
}
}
输出是:
true
1.0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9.0
10.0
如何在完成任务后评估allTaskDone?换句话说,做出这样的事情:
1.0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9.0
10.0
true
提前感谢!
答案 0 :(得分:0)
timer.schedule中的1(new someFunction(),0,1);意味着它将每隔1ms重复一次任务。
以下代码将模仿您的互动,并按照您的意愿行事。我正在使用ScheduledExecutorService而不是Timer。
final FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
public String call() throws Exception {
int counter = 0;
boolean finished = false;
while (!finished) {
System.out.println("work in progress..." + counter);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter += 1;
if (counter > 5) {
finished = true;
return "work done";
}
}
return "not finished";
}
});
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(task, 0, 1, TimeUnit.MILLISECONDS);
String done = task.get();
scheduler.shutdown();
System.out.println(done);