简体   繁体   中英

TimerTask in Java

Currently my output is the equation and answer before the countdown. I want the equation, countdown, and answer in that order. I have tried switching around parts, but I am not sure there is a smart way to do this.

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);

        int num1 = (int) (Math.random()*10);

   int num2 = (int) (Math.random()*10);

        System.out.println(num1);

            System.out.println("+");

    System.out.println(num2);

    int addition = num1 + num2;

    System.out.println("=");

    System.out.println(addition);

    }
}

    class Task extends TimerTask 

{

    int i=4;

    @Override

    public void run() {

        i--;
        if(i==3)
            System.out.println("3 >>>");
        if(i==2){
            System.out.println("2 >>>");
        }
        if(i==1){
            System.out.println("1 >>>");
            cancel();    

            System.exit(0);
        }   
    }
}

You can first print out the equation. Next start your timer. Then, in your main thread, use wait() to pause the tread. Then after your timer finishes it last iteration call notify() . finally have the answer be printed.

See also: http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html

You could do something like this. Note that I added the result to the constructor of Task , and I added the System.out.println before exit.

import java.util.Timer;
import java.util.TimerTask;

public class S1p4 {

  public static void main(String[] args) {
    Timer timer = new Timer();
    int num1 = (int) (Math.random() * 10);
    int num2 = (int) (Math.random() * 10);
    int addition = (int) num1 + num2;
    System.out.println(num1);
    System.out.println("+");
    System.out.println(num2);
    // Add the result to the task.
    Task task = new Task(addition);
    timer.schedule(task, 1000, 1000);
  }
}

class Task extends TimerTask {
  // Store the result.
  private int result;

  // Construct a Task with the result.
  public Task(int result) {
    super();
    this.result = result;
  }

  // How many times to run.
  int i = 4;

  @Override
  public void run() {
    i--;
    if (i == 3) {
      System.out.println("3>>>");
    } else if (i == 2) {
      System.out.println("2>>>");
    } else {
      System.out.println("1>>>");
      cancel();
      // The timer is done print the result.
      System.out.println("The result was " + result);
      System.exit(0);
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM