1

i am working on a Java application and i reach a point where i want to pause the execution for few seconds ( chosen by the user ) and resume it latter ..and here is a simple code :

Public Class myApp
{
    static public main()
    { 
       int seconds=10;
       // do couple of things 
       try {
                   Thread.sleep(10*1000);
               } catch (InterruptedException ex) {

                   Logger.getLogger(myApp.class.getName()).log(Level.SEVERE,    null,      ex);
               }
    }

i want now to give the user a chance by clicking on a button to resume the execution even before the time is up . is this possible using "Thread.sleep()" ? or there is another way to pause App and resume it ?

user2746896
  • 27
  • 2
  • 7

3 Answers3

1

You can use wait in place of sleep to pause the thread execution. Then you can use notify or notifyAll to wake up the waiting thread.

Terry Li
  • 16,870
  • 30
  • 89
  • 134
1

Use CountDownLatch

Public Class myApp
{
    static CountDownLatch countDownLatch = new CountDownLatch(1);

    static public main()
    {        
       try {
            countDownLatch.await(10000, TimeUnit.MILLISECONDS);
       } catch (InterruptedException ex) {
            // Logging
       }
    }
}

and you can call countDownLatch.countDown() method from the resume button on click

shazin
  • 21,379
  • 3
  • 54
  • 71
0

You can use interrupt to cancel the sleep, here are more info: http://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

stdapsy
  • 154
  • 1
  • 1
  • 8