Java Programming - Threads - Discussion

8. 

What will be the output of the program?

public class ThreadDemo 
{ 
    private int count = 1; 
    public synchronized void doSomething() 
    { 
        for (int i = 0; i < 10; i++) 
            System.out.println(count++); 
    } 
    public static void main(String[] args) 
    { 
        ThreadDemo demo = new ThreadDemo(); 
        Thread a1 = new A(demo); 
        Thread a2 = new A(demo); 
        a1.start(); 
        a2.start(); 
    } 
} 
class A extends Thread 
{ 
    ThreadDemo demo; 
    public A(ThreadDemo td) 
    { 
        demo = td; 
    } 
    public void run() 
    { 
        demo.doSomething(); 
    } 
}

[A]. It will print the numbers 0 to 19 sequentially
[B]. It will print the numbers 1 to 20 sequentially
[C]. It will print the numbers 1 to 20, but the order cannot be determined
[D]. The code will not compile.

Answer: Option B

Explanation:

You have two different threads that share one reference to a common object.

The updating and output takes place inside synchronized code.

One thread will run to completion printing the numbers 1-10.

The second thread will then run to completion printing the numbers 11-20.


Trtw said: (May 15, 2014)  
I think it's wrong: one thread will print numbers from 2 to 11.

The second thread will print numbers from 12 to 22.

Jimmie said: (Nov 2, 2014)  
@Trtw.

The count ++assignment on line 7 only increments the value of count after the print statement so it starts printing from 1.

If the assignment was written as ++count you would be correct.

Jacek said: (Nov 30, 2014)  
I am a beginner, but I choose D because I noticed that for do not have "{}" but when I put it to Eclipse it not compiled because of line 20: "class A extends Thread".

Priyanka said: (Sep 2, 2016)  
I think ThreadDemo should implement Runnable. It compile an error.

Chintan Akkian said: (Mar 27, 2019)  
There are 2 thread sharing one reference object thread.

Therefore loop will execute 2 times value of count will increase.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.