Java Programming - Threads - Discussion

Discussion Forum : Threads - Finding the output (Q.No. 7)
What will be the output of the program?
class s implements Runnable 
    int x, y; 
    public void run() 
        for(int i = 0; i < 1000; i++) 
                x = 12; 
                y = 12; 
        System.out.print(x + " " + y + " "); 
    public static void main(String args[]) 
        s run = new s(); 
        Thread t1 = new Thread(run); 
        Thread t2 = new Thread(run); 
It print 12 12 12 12
Compilation Error
Cannot determine output.
Answer: Option

The program will execute without any problems and print 12 12 12 12.

15 comments Page 1 of 2.

Mohammed Parvez said:   3 years ago
For loop is a trap, If you provide braces for 'for' loop then it prints as much as condition.

Pavan said:   6 years ago

You can declare it with lower case, but the convention is to start with a capital letter.

Ayush said:   7 years ago
The for loop is not having braces so the synch block is in for loop and other code is not in loop.

Lefteris said:   7 years ago
This cause a compilation error as NO class in Java can start with a lowercase letter!

Please help me.

Rakesh said:   8 years ago
Explain the usage of synchronized?

Rochet2 said:   9 years ago
@Aghnar just spoke out my mind.

I looked into it a bit and it seems that the documentation did not say it was thread safe.

It can be that the implementation of it /may/ still be, but should not trust assumptions.

Aghnar said:   9 years ago
The synchronized block is a trap. Actually the two threads can
execute the System.out.print(x + " " + y + " ");

So if this code 'System.out.print(x + " " + y + " ")' is not thread safe (which I think is possible, I have to look into the source), the result can be indeterminate.

Sunil said:   9 years ago
If I remove synchronize block then what happen ?

Vishal said:   1 decade ago
Hello Guys

Here for loop is not having any relation with System.out.print(x + " " + y + " "); after iterating for 1000 times only once this line of code will be executed by thread1,and once the lock is released thread2 will print the System.out.print(x + " " + y + " "); after iterating 1000 times So o/p will between
12 12 12 12

Pravin chavan said:   1 decade ago
Hello guys.

There only 2 threads are present. So when the 1st thread are in run method then it print 12 and 12 at that point the 2nd thread is in runnable state (i.e he is weighting for the control of run method) , when the thread1 finished its then thread2 is access the run method. And it prints 12, 12.

So o/p= 12, 12, 12, 12.

Post your comments here:

Your comments will be displayed after verification.