The idea is as follows: I add an entry to the database, but before that I want to “add” the adding process a little, displaying the following values ​​in the console: 10% ... 20% ... 30% ... etc. until the end ... at the end to bring out the word "Added!". Each percent must be withdrawn at intervals of a second, i.e. first a second without information, then after a second output 10% ..., after another second 20% ... and so on. It seems everything works out, but the word "Added" crashes right at the very beginning of the program, and indeed the whole program flies ahead with its life without waiting until it works until the end of the code block with the timer. Please explain how to write correctly so that the program waits until the end of work in the timer block and only then, depending on the success or failure of adding the record, worked further.

import java.util.Timer; import java.util.TimerTask; public class MyTimer{ public static int proc = 0; public static void main(String[] args){ final Timer writeTime = new Timer(); writeTime.schedule(new TimerTask() { @Override public void run(){ if(proc < 100) { proc = proc + 10; System.out.print(proc + "%..."); } } },1000,1000); System.out.println("Добавлен"!); } } 

    1 answer 1

    If Timer not critical

     //создаем новый поток Thread mThread = new Thread(new Runnable() { // то что будет выполняться в потоке public void run() { int proc = 0; while(proc < 100) { proc = proc + 10; System.out.print(proc + "%..."); try { Thread.sleep(1000); // задержка 1000 мс } catch (InterruptedException e) { e.printStackTrace(); } } // можно в это место перенести вывод и убрать Thread.join(); тогда основной поток висеть не будет } }); //запускаем поток mThread.start(); //подождем пока поток завершит свое исполнение mThread.join(); System.out.println("Добавлен"); 
    • one
      IMHO, for(int proc=0; proc <= 100; proc += 10) instead of while will be prettier) - Evgeniy
    • one
      @Evgeniy, perhaps, the taste and color as they say ... Just as it so happened, that cycles of this kind (which sound like "I'm doing for now ...") I draw in while - JVic
    • Many thanks, very helpful! Exactly what is needed! - Tim Leyden
    • @Victor, and with the help of a timer can this be done? I pushed the conditions into the run () method, but I can't figure out how to make the entire program wait until the timer runs and then continue working - Tim Leyden
    • one
      @TimLeyden no timer does not have the ability to "hang" the main thread while it runs itself, it is designed to cycle the code without loading the main thread. If you still want to do this in the timer, you will have to do everything like this: if(proc < 100) {... } else System.out.println("Добавлен"); . This will bring you "Added" at the right time after the timer has run. And everything that will be written below the timer ad will be executed without looking at the timer - JVic