Java Programming - Threads - Discussion

6. 

What will be the output of the program?

class s1 extends Thread
{ 
    public void run() 
    { 
        for(int i = 0; i < 3; i++) 
        { 
            System.out.println("A"); 
            System.out.println("B"); 
        } 
    } 
} 
class Test120 extends Thread 
{ 
    public void run() 
    { 
        for(int i = 0; i < 3; i++) 
        { 
            System.out.println("C"); 
            System.out.println("D"); 
        } 
    } 
    public static void main(String args[]) 
        { 
        s1 t1 = new s1(); 
        Test120 t2 = new Test120(); 
        t1.start(); 
        t2.start(); 
    } 
}

[A]. Compile time Error There is no start() method
[B]. Will print in this order AB CD AB...
[C]. Will print but not be able to predict the Order
[D]. Will print in this order ABCD...ABCD...

Answer: Option C

Explanation:

We cannot predict the order in which threads are going to run.


Deepss said: (Sep 30, 2011)  
I got following output!!...
A
B
A
B
A
B
C
D
C
D
C
D
The output is very much predictable ,the threads are being called on seperate instances t1 and t2...so first start method of t1thread will be called its run executed then followed by start of t2 thread.

Rajesh said: (Mar 26, 2014)  
Yep.. me too got the same output.
A
B
A
B
A
B
C
D
C
D
C
D

Its easily predictable.

Prashant said: (Mar 10, 2016)  
A
B
A
B
A
B
C
D
C
D
C
D
We got this output because of there no make a Thread class object. It's work simply a normal program. We should make a thread class object and pass a class reference in Thread class constructor.

Nik said: (Aug 30, 2016)  
Without thread object can a start method be called?

Prashantp224 said: (Apr 4, 2017)  
I got an output as,

A
B
A
B
A
B
C
D
C
D
C
D

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.