Java Programming - Threads - Discussion

Discussion Forum : Threads - Finding the output (Q.No. 8)
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(); 
    } 
}
It will print the numbers 0 to 19 sequentially
It will print the numbers 1 to 20 sequentially
It will print the numbers 1 to 20, but the order cannot be determined
The code will not compile.
Answer: Option
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.

Discussion:
5 comments Page 1 of 1.

TrTw said:   1 decade ago
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:   10 years ago
@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:   9 years ago
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:   8 years ago
I think ThreadDemo should implement Runnable. It compile an error.

Chintan Akkian said:   5 years ago
There are 2 thread sharing one reference object thread.

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

Post your comments here:

Your comments will be displayed after verification.