AlgoMantra

AlgoMantra Java, Data Structures, Algorithm, NIO, Multithreading

24/07/2015

Test post....

New Post added at:Thread sleep call demo in Javahttp://algomantra.co.in/?p=105
24/07/2015

New Post added at:
Thread sleep call demo in Java
http://algomantra.co.in/?p=105

There may be multiple occasions where you may want the current thread going to sleep for some timeout. While we know that Thread.sleep() call is a way to go, there are couple of other points you should also be caring about:

1. Do you want a minimum guaranteed time out for which thread should sleep even though the thread has been interrupted?


2. It is always a good idea to have a while loop and check the condition before you come out of the sleep call block and continue normally.

Here is a possible demo which demonstrate the idea:
[java]
public class ThreadSleepDemo {
public static void sleepCallDemo(long waitTimeInMillis){
while(waitTimeInMillis > 0L){
long then = System.currentTimeMillis();
try{
Thread.sleep(waitTimeInMillis);
}catch(InterruptedException iEx){
}
long now = System.currentTimeMillis();
waitTimeInMillis = waitTimeInMillis – (now – then);
}
}
public static void main(String[] args) {
long wtMillis = 5 * 1000L; // 5 sec
System.out.println(“Demo for main thread sleeping for AT LEAST “+ wtMillis + ” milliseconds”);
long beforeSleep = System.currentTimeMillis();
sleepCallDemo(wtMillis);
long afterSleep = System.currentTimeMillis();
System.out.println(“The current thread: \””+ Thread.currentThread().getName() +”\” went to SLEEP for ” +(afterSleep – beforeSleep) +” milliseconds.”);
}
}
[/java]
Disclaimer: THE SAMPLE CODE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AlgoMantra OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) SUSTAINED BY YOU OR A THIRD PARTY, HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, OR STRICT LIABILITY ARISING IN ANY WAY OUT OF THE USE OF THIS SAMPLE CODE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Address

Marathalli
Bangalore
560037

Alerts

Be the first to know and let us send you an email when AlgoMantra posts news and promotions. Your email address will not be used for any other purpose, and you can unsubscribe at any time.

Share