This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
Hi Ranchers please explain the following codes.when i run it gives output 00224466 is it vary or same bcaz 2 thread instance created.
but options are A 0 2 4 4 6 8 10 6 B 0 2 4 6 8 10 2 4 C 0 2 4 6 8 10 12 14 D 0 0 2 2 4 4 6 6 8 8 10 10 12 12
questions : class Thread1 { int x=0; public class Runner implements Runnable { public void run() { int cur=0; for (int i=0;i<4 ;i++ ) { cur=x; System.out.println(cur +" "); x=cur+2; } } }; public static void main(String[] args) { (new Thread1()).go(); } public void go() { Runnable r1=new Runner(); (new Thread(r1)).start(); (new Thread(r1)).start(); } }
The value of cur depends on x, which is in fact a class variable whose value keeps on updating every time run() is executed.
So whatever the case may be, at every single execution of for loop (by any thread) x is updated and hence the (local) cur variable is updated printing values 0 2 4 6 8 10 12 14
Yes the Answer is C. the output is predictable well.
as Gitesh said, we are printing cur, which depends variable x, which is a class variable.
so 2 Threads, 4+4 times the value of x is modified and printed via c.
simple way to understand, comment the //L2 in the below code and run it will run the loop 4 times leaving 0 2 4 6 as output. then de-comment //L2 ad run you will get the output as option c
class JRThread1 { int x=0;
public class Runner implements Runnable { public void run() { int cur=0; for (int i=0;i<4 ;i++ ) { cur=x; System.out.print(cur +" "); x=cur+2; } } };
public static void main(String[] args) { (new JRThread1()).go(); }
public void go() { Runnable r1=new Runner(); (new Thread(r1)).start(); //L1 (new Thread(r1)).start(); //L2 } }
Satya Maheshwari
Ranch Hand
Joined: Jan 01, 2007
Posts: 368
posted
0
I would still say, the output is unpredictable. Here's my understanding.
1.x is a class variable 2.x is shared between 2 threads. 3.x is being modified in run() through x=cur+2. 4.Let's say
So above you see that the output is something like 0 0... Still in another way it could be 0 2 4 6 8 ...
Hence I do not think it is possible to predict the output.Though your OS may always give the output 0 2 4 6 8 ... (or something else)
I did some minor modification to your code to verify:
And the output was: 0 0 2 2 4 4 6 6 [ August 31, 2007: Message edited by: Satya Maheshwari ]
srinibash udayasingh
Greenhorn
Joined: Jul 09, 2007
Posts: 22
posted
0
Hi still it is confuse to me.in my machine it shows 0 0 2 2 4 4 6 6.