Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to check elapsed milliseconds using Thread.Sleep in for loop with Java

2 Answers

0 votes
public class Program {
    public static void testSpeed(int ms) {
        long currentTime = System.currentTimeMillis();

        for (int i = 0; i < 1000; i++) {
            try {
                Thread.sleep(ms);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // restore interrupt status
                System.out.println("Sleep interrupted at iteration " + i);
                return;
            }
        }

        System.out.println("Executed in " + (System.currentTimeMillis() - currentTime) + " ms");
    }

    public static void main(String[] args) {
        testSpeed(1);
    }
}



/*
run:

Executed in 1090 ms

*/

 



answered Jul 9, 2025 by avibootz
0 votes
import java.util.concurrent.TimeUnit;

public class Program {
    public static void testSpeed(int ms) {
        long startTime = System.currentTimeMillis();

        for (int i = 0; i < 1000; i++) {
            try {
                TimeUnit.MILLISECONDS.sleep(ms); // Sleeps for ms milliseconds
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // Restore interrupt status
                System.out.println("Sleep interrupted");
                return;
            }
        }

        long elapsed = System.currentTimeMillis() - startTime;
        System.out.println("Executed in " + elapsed + " ms");
    }
    
    public static void main(String[] args) {
        testSpeed(1);
    }
}



/*
run:

Executed in 1080 ms

*/

 



answered Jul 9, 2025 by avibootz

Related questions

1 answer 191 views
1 answer 130 views
130 views asked Jan 29, 2024 by avibootz
4 answers 2,695 views
2,695 views asked Mar 24, 2021 by avibootz
1 answer 153 views
...