0

I'm using threads in java to print a counter and increase it every one second. I want the counter to be printed on the previous counter value, but what is actually happening is that the counter is being printed in a new place. How can I do that?

Here is the code and the output in Netbeans:

package threads;

public class Threads extends Thread {

    public static int counter = 0;
    
    static synchronized void incrementCounter() {
          System.out.print(counter );
          counter++;
     }

     @Override
     public void run() {
          while(counter<1000){
               incrementCounter();              
              try {
                  sleep(1000);
              } catch (InterruptedException ex) {

              }
          }
     }

     public static void main(String[] args) {
          Threads te = new Threads();         
          te.start();
     } 
}

This is the output:

012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061...
Ted Klein Bergman
  • 8,342
  • 4
  • 24
  • 45

1 Answers1

0

You can achieve that by replacing your

System.out.print(counter );

By

System.out.printf("%s", "\u0008\u0008\u0008\u0008" + counter );

\u0008 is Backspace.

pringi
  • 3,149
  • 5
  • 31
  • 39
  • 1
    You should probably change the number of backspaces according to what's been printed, as otherwise it'll delete other content. – Ian Newson Mar 23 '22 at 18:17