Java Programming - Threads - Discussion

Discussion Forum : Threads - Finding the output (Q.No. 2)
2.
What will be the output of the program?
class MyThread extends Thread 
{
    public static void main(String [] args) 
    {
        MyThread t = new MyThread();
        t.start();
        System.out.print("one. ");
        t.start();
        System.out.print("two. ");
    }
    public void run() 
    {
        System.out.print("Thread ");
    }
}
Compilation fails
An exception occurs at runtime.
It prints "Thread one. Thread two."
The output cannot be determined.
Answer: Option
Explanation:

When the start() method is attempted a second time on a single Thread object, the method will throw an IllegalThreadStateException (you will not need to know this exception name for the exam). Even if the thread has finished running, it is still illegal to call start() again.

Discussion:
8 comments Page 1 of 1.

Narashimha said:   5 years ago
MyThread t = new MyThread();
t.start();
System.out.print("one. ");
t.start();

Here am writing two methods are calling you are defined but coming to any runtime exception Thread class is predefined class class having run() method when the calling this method in two times or more than two times coming to the exception at runtime why?

Harold said:   8 years ago
I have a weird question, is it possible to detect this issue in compile time? Similar to multiple variable definitions.

Devi said:   9 years ago
Which class to have illegal exception?

Pragati said:   9 years ago
Why it is illegal to call start() again?

Priya said:   9 years ago
Why it is illegal to call start() again?

Ananya said:   1 decade ago
When/why this exception occurs?

King said:   1 decade ago
You can check by writing these statements in try-catch block and print exception in catch block. So you can see the Exception.

Samip said:   1 decade ago
How can we know if this will cause runtime or compiletime error ?

Post your comments here:

Your comments will be displayed after verification.