-1

I have a problem about Timer in java. When I run the code below, a.start(0), a.start(1) and a.start(2) are being printed at the same time and the output is like 02121010120010122012102 but I want to be printed in order like 00000001111111222222222

How to do this?

public class Main {

public static void main(String[] args) {

    A a = new A();
    a.start(0);
    a.start(1);
    a.start(2);     
}

public class A {

public void start(int x)
{
    Timer myTimer=new Timer();
    TimerTask task=new TimerTask() {
        int counter=0;
           @Override
           public void run() {
                  System.out.print(x);
                  counter++;
                  if(counter>=10)
                         myTimer.cancel();
           }
    };

    myTimer.schedule(task,0,300);
}

}

Towfik Alrazihi
  • 536
  • 3
  • 8
  • 25
tntnt44
  • 9
  • 2
  • 6
    And why do you think that these timers should wait for each other? – Tom Aug 31 '16 at 12:55
  • All three timers are scheduled at the same time. This means that they should run like they do for you. – Slimu Aug 31 '16 at 12:56

2 Answers2

1

You have three tasks; and the idea is that they run independently of each other. If you want them to be "synchronized" somehow; then well, you have to use some form synchronization.

There are many ways to get there. Objects in Java can use wait/notify to create such a logic; or they can use some form of queue object to "exchange" such information.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

You can do this with synchronized block of code. Try this

public void run() {
    synchronized(this) {
        System.out.print(x);
        counter++;
        if(counter>=10)
            myTimer.cancel();
        }
    }
}
Jhonny007
  • 1,698
  • 1
  • 13
  • 33
Pratyush
  • 68
  • 8