JAVA-4

Q.4 Write an application that execute two Threads. One thread display “BCA” every 1000 milliseconds and the order displays “MCA” every 3000 milliseconds. Create the threads by extending the thread class.

Solution :- 

class BCAThread extends Thread {
    public void run() {
        try {
            while (true) {
                System.out.println("BCA");
                Thread.sleep(1000); // 1000 milliseconds = 1 second
            }
        } catch (InterruptedException e) {
            System.out.println("BCA Thread Interrupted");
        }
    }
}

class MCAThread extends Thread {
    public void run() {
        try {
            while (true) {
                System.out.println("MCA");
                Thread.sleep(3000); // 3000 milliseconds = 3 seconds
            }
        } catch (InterruptedException e) {
            System.out.println("MCA Thread Interrupted");
        }
    }
}

public class ThreadDemo {
    public static void main(String[] args) {
        BCAThread bcaThread = new BCAThread();
        MCAThread mcaThread = new MCAThread();
        
        bcaThread.start();
        mcaThread.start();
    }
}

Output

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.