What will be the result of the following code compilation and execution?

public class SleepMain {
    public static void main(String... args) {
        Thread t = new MyThread();
        for (int i = 1; i <= 5; i++) {
            System.out.print(i + " ");
            try {
  t.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("Interrupted in main");
            }
        }
    }

    static class MyThread extends Thread {
public void run() {
            for (int i = 1; i <= 5; i++) {
                System.out.print(i + " ");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    System.out.println("Interrupted in myThread");
                }

            }
        }
    }
}
Explanation
t.start() method should be called to start the second thread. Only original thread will work without it.
Sleep() method of the Thread class is static, therefore the t.sleep() call will result into the current thread, i.e., main, being made asleep.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes