问题
I want my program to print Hello User, a ten seconds later print Ten Seconds Have Gone By, finally, a few seconds later print Goodbye User. I just don't know what or how to start to do this. Thanks
Here's the code:
import java.util.Timer;
import java.util.TimerTask;
public class S1p4 {
public static void main(String[] args) {
Timer timer = new Timer();
Task task = new Task();
timer.schedule(task, 1000, 1000);
}
}
class Task extends TimerTask {
int i=1;
@Override
public void run() {
i++;
System.out.println("Hello User");
if(i<=10){
System.out.println("Ten Seconds Have Gone By");
}
System.out.println("Goodbye User");
cancel();
System.exit(0);
}
}
EDIT 1: It would run good if I take out System.exit();, but what would I replace it with? Because I don't want a program that I have to stop.
回答1:
Try this :
class Task extends TimerTask {
int i=0;
@Override
public void run() {
i++;
if(i==1)
System.out.println("Hello User");
if(i==10){
System.out.println("Ten Seconds Have Gone By");
}
if(i==13){
System.out.println("Goodbye User");
cancel();
}
}
}
o/p :
First time it prints : Hello User After 10 sec it prints : Ten sec has passed. After 13 sec : Goodby User
回答2:
The timer you're using is ok, we just need to apply Thread.sleep to resolve your problem.
class Task extends TimerTask {
@Override
public void run() {
System.out.println("Hello User");
try {
Thread.sleep(10000);
System.out.println("Ten Seconds Have Gone By");
Thread.sleep(5000);
System.out.println("Goodbye User");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
来源:https://stackoverflow.com/questions/20039949/timer-and-timertask-java