How to write a Java time out code?

Posted on 2008-11-04
Last Modified: 2013-11-23
How can I make this while loop only run 1000ms or 1s?
while (true){

Thanks for reading my question!
Question by:guochu
    LVL 86

    Expert Comment

    How about the following:
    LVL 86

    Expert Comment


    while (counter < 1000){
    // (Enclose in exception handling)

    Open in new window

    LVL 5

    Accepted Solution

    CEHJ, I didn't understand the logic behind the solution provided by you. Are you assuming that conuter is being incremented exactly once per millisecond ?

    guochu, if you really need the value of "counter" after executing this loop for exactly 1s, then refer to the attached code snippet else if you simply want to make your application rest for 1s, you may replace this loop with the following statement :

    try { Thread.sleep(1000) } catch (InterruptedException e) {}

    long starttime = System.currentTimeMillis();
    long endtime = starttime + 1000;
    while (endtime >= System.currentTimeMillis()) {

    Open in new window


    Author Closing Comment


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    6 Surprising Benefits of Threat Intelligence

    All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

    INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
    Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
    Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
    This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

    779 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now