• Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread Output

 
SUBHADIP BERA
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please help with the possible output:

public class Ex13
{
int x;
class Runner implements Runnable
{
public void run()
{
int current = 0 ;
for(int i=0;i<4;i++){
current = x;
System.out.print(current +", ");
x=current+2;
}
}
}

public static void main(String []S)
{new Ex13().go();}


public void go(){
Runner r1 = new Runner();
new Thread(r1).start();
new Thread(r1).start();
}
}
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Subhadip,

this seems to be your first posting here, so

Welcome to the ranch!



It is true, when you say possible output.
Theoretically, the output can be different on different machines.
This is because, the first thread could be paused anywhere in the middle of the for-loop, and the second thread starts anew with counting.
And when the switching from one thread to another occurs is system dependent.
But in reality, the loop is so short that I would guess, the loop is over in all cases, before the second thread would have a chance to run.

I modified your original a little to show the names of the thread:

produces all even numbers up to fourteen:

A0, A2, A4, A6, B8, B10, B12, B14,

the first four digits from the first(A), and the second four digits from the second thread(B). Both threads share the variable x, so the second thread won't start with zero again. And x is always incremented again.
But notice, I put a comment somewhere in the loop. If you comment it out, the current thread will set to Blocking, and the other thread will have a chance to run.
I only put this line in to simulate machines, that have an extremely short time slice (don't think such machines realy exist). If it runs that way, thread one and two always change their position just in the middle of the loop.

In this case the output will be
A0, B0, A2, B2, A4, B4, A6, B6,


because in between the lines
current = x;
and
x = current + 2;

the thread blocks, and the other one runs, taking the "old" x.


OK so far?


Yours,
Bu.
[ April 29, 2007: Message edited by: Burkhard Hassel ]
 
SUBHADIP BERA
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Many many Thanks
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!

Similar Threads