How to use thread sleep in Java

4 Answers

0 votes
public class UseThreadSleep_Java {
    public static void main(String args[]) {
        try {
            long start = System.currentTimeMillis();
            Thread.sleep(1000);
            System.out.println("Sleep time in ms = " + (System.currentTimeMillis() - start));
 
        } catch (InterruptedException ie) {
            System.out.println(ie);
        }
    }
}

 
 
/*
run:
 
Sleep time in ms = 1000
 
*/    

 



answered Mar 24, 2021 by avibootz
edited Sep 1, 2024 by avibootz
0 votes
import java.util.concurrent.TimeUnit;

public class MyClass {
    public static void main(String[] args) {
        try {
            for (int i = 1; i < 6; i++) {
                System.out.println(i);
                TimeUnit.SECONDS.sleep(1);
            }
        } catch (InterruptedException ie) {
            System.out.println("Thread error: " + ie);
        }
    }
}
  
  
  
  
/*
 
run:
 
1
2
3
4
5
 
*/

 



answered Mar 24, 2021 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        Thread mainThread = Thread.currentThread();
          
        System.out.println("Current thread: " + mainThread);
          
        try {
            long start = System.currentTimeMillis();
            Thread.sleep(2000);
            System.out.println("Sleep time in ms = " + (System.currentTimeMillis() - start));
        }
        catch (InterruptedException ie) {
            System.out.println("Exception: " + ie);
        }
    }
}
  
  
  
  
/*
run:
  
Current thread: Thread[main,5,main]
Sleep time in ms = 2000
  
*/

 



answered Mar 25, 2023 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        Thread mainThread = Thread.currentThread();
         
        System.out.println("Current thread: " + mainThread);
         
        mainThread.setName("MyThread");
        System.out.println("Current thread: " + mainThread);
         
        try {
            for (int i = 1; i <= 7; i++) {
                System.out.println("i = " + i);
                Thread.sleep(500);
            }
        }
        catch (InterruptedException e) {
            System.out.println("Exception: " + e);
        }
    }
}
 
 
 
 
/*
run:
 
Current thread: Thread[main,5,main]
Current thread: Thread[MyThread,5,main]
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
 
*/

 



answered Mar 25, 2023 by avibootz

Related questions

1 answer 142 views
142 views asked Jan 29, 2024 by avibootz
1 answer 207 views
1 answer 115 views
115 views asked Sep 1, 2024 by avibootz
1 answer 99 views
99 views asked Sep 1, 2024 by avibootz
1 answer 109 views
109 views asked Sep 1, 2024 by avibootz
1 answer 106 views
106 views asked Sep 1, 2024 by avibootz
...