How to sleep a thread in Java

1 Answer

0 votes
class MyThread implements Runnable {
    public void run() {
        try {
            for (int i = 1; i <= 3; i++) {
                System.out.println("Thread " + Thread.currentThread().getId() + " is running");
    
                Thread.sleep(2000);
            }
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}
 
public class Program {
    public static void main(String[] args) {
        Thread trd1 = new Thread(new MyThread());
        Thread trd2 = new Thread(new MyThread());
        Thread trd3 = new Thread(new MyThread());
 
        trd1.start();
        trd2.start();
        trd3.start();
    }
}
 
 
  
/*
run:
  
Thread 17 is running
Thread 15 is running
Thread 16 is running
Thread 17 is running
Thread 15 is running
Thread 16 is running
Thread 17 is running
Thread 15 is running
Thread 16 is running
  
*/

 



answered Jan 29, 2024 by avibootz

Related questions

4 answers 2,963 views
2,963 views asked Mar 24, 2021 by avibootz
1 answer 325 views
1 answer 214 views
214 views asked Sep 1, 2024 by avibootz
1 answer 195 views
195 views asked Sep 1, 2024 by avibootz
...