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,722 views
2,722 views asked Mar 24, 2021 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
...