Timer and TimerTask Java

让人想犯罪 __ 提交于 2020-01-06 15:38:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!