Java Programming - Threads - Discussion

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 ");
    }
}

[A]. Compilation fails
[B]. An exception occurs at runtime.
[C]. It prints "Thread one. Thread two."
[D]. The output cannot be determined.

Answer: Option B

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.


Samip said: (Jun 29, 2012)  
How can we know if this will cause runtime or compiletime error ?

King said: (Jul 2, 2012)  
You can check by writing these statements in try-catch block and print exception in catch block. So you can see the Exception.

Ananya said: (Jun 2, 2013)  
When/why this exception occurs?

Priya said: (Jan 15, 2014)  
Why it is illegal to call start() again?

Pragati said: (Aug 13, 2014)  
Why it is illegal to call start() again?

Devi said: (Sep 16, 2014)  
Which class to have illegal exception?

Harold said: (Aug 18, 2015)  
I have a weird question, is it possible to detect this issue in compile time? Similar to multiple variable definitions.

Narashimha said: (Jun 5, 2018)  
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?

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.