Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

How to write a Java time out code?

Posted on 2008-11-04
4
Medium Priority
?
2,912 Views
Last Modified: 2013-11-23
How can I make this while loop only run 1000ms or 1s?
while (true){
    counter++;
}

Thanks for reading my question!
0
Comment
Question by:guochu
  • 2
4 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 22881881
How about the following:
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 22881890

while (counter < 1000){
    Thread.sleep(100);
    counter+=100;
}
 
// (Enclose in exception handling)

Open in new window

0
 
LVL 5

Accepted Solution

by:
muktajindal earned 500 total points
ID: 22883394
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()) {
	counter++;
}

Open in new window

0
 

Author Closing Comment

by:guochu
ID: 31513318
Thanks!!!
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses
Course of the Month10 days, 19 hours left to enroll

572 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