JAVA-13

Q.13 Write an application that creates and start three threads, each thread is instantiated from the same
class. It executes a loop with 5 iterations. First thread display “BEST”, second thread display “OF” and
last thread display “LUCK”. All threads sleep for 1000 ms. The application waits for all threads to
complete and display a message.

Solution :- 

class MessageThread extends Thread {
    private String message;

    public MessageThread(String message) {
        this.message = message;
    }

    public void run() {
        try {
            for (int i = 0; i < 5; i++) {
                System.out.println(message);
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            System.out.println("Thread interrupted: " + e.getMessage());
        }
    }
}

public class ThreadExample {
    public static void main(String[] args) {
        MessageThread t1 = new MessageThread("BEST");
        MessageThread t2 = new MessageThread("OF");
        MessageThread t3 = new MessageThread("LUCK");
        
        t1.start();
        t2.start();
        t3.start();
        
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            System.out.println("Main thread interrupted: " + e.getMessage());
        }
        
        System.out.println("All threads have completed execution.");
    }
}

TRY IT YOURSELF

Leave a Reply

Your email address will not be published. Required fields are marked *

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.