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

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,709 questions

55,473 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 244 views
1 answer 176 views
176 views asked Jan 29, 2024 by avibootz
4 answers 2,784 views
2,784 views asked Mar 24, 2021 by avibootz
1 answer 200 views
...