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 2 of 2.

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();
}
}

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

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

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

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


Post your comments here:

Your comments will be displayed after verification.