Java Programming - Threads - Discussion

Discussion Forum : Threads - Finding the output (Q.No. 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++) 
    public static void main(String[] args) 
        ThreadDemo demo = new ThreadDemo(); 
        Thread a1 = new A(demo); 
        Thread a2 = new A(demo); 
class A extends Thread 
    ThreadDemo demo; 
    public A(ThreadDemo td) 
        demo = td; 
    public void run() 
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

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.

5 comments Page 1 of 1.

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.

Priyanka said:   8 years ago
I think ThreadDemo should implement Runnable. It compile an error.

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".

Jimmie said:   10 years ago

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.

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.

Post your comments here:

Your comments will be displayed after verification.