Java Programming - Threads - Discussion

Discussion Forum : Threads - Finding the output (Q.No. 7)
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++) 
            synchronized(this) 
            { 
                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); 
        t1.start(); 
        t2.start(); 
    } 
}
DeadLock
It print 12 12 12 12
Compilation Error
Cannot determine output.
Answer: Option
Explanation:

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

Discussion:
15 comments Page 1 of 2.

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

Sanchi said:   2 decades ago
It is good and easy to understand.

Kunal said:   1 decade ago
Could you please explain how the flow will work here ?

Abhinav said:   1 decade ago
Where is the body of the for loop?

Pramod said:   1 decade ago
Please explain me whole code.

Robin said:   1 decade ago
Just run this code you can understand it.

class s implements Runnable
{
int x, y;
public void run()
{
for(int i = 0; i < 1000; i++)

synchronized(this)
{
System.out.println(i);//this code execute 1000 //times ie this block synchronized 1000 time
x = 12;
y = 12;
}
System.out.print(x + " " + y + " ");// but for loop has //no effect on this block.
}
public static void main(String args[])
{
s run = new s();
Thread t1 = new Thread(run);
Thread t2 = new Thread(run);
t1.start();
t2.start();
}
}

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.

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

Sunil said:   1 decade ago
If I remove synchronize block then what happen ?

Aghnar said:   1 decade 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.


Post your comments here:

Your comments will be displayed after verification.