Originally posted by amit sanghai:
To Sasi,
I didnot understand your answer to the first question!!![/B]
Hi
I have explained this in one my earlier postings...I am giving it again down below:
I would like to explain this with an example
/file: example.java
class example extends Thread
{
public increment localIncr;
example( increment var)
{
localIncr = var;
}
public static void main(
String a[])
{
increment obj = new increment();
example one = new example(obj);
example two = new example(obj);
one.start();
two.start();
}
public void run()
{
localIncr.addone();
}
}
class increment
{
int incrVar;
public void addone()
{
incrVar++;
System.out.println("var Val : "+ incrVar);
}
}
Here in above the example class extends Thread class and creates two variables one and two of class exapmle in the main method. To the constructor of the example class I am passing a reference to
an increment object. you can see that while creating two thread one and two I am passing the same reference obj. Basically this increment object is common to both the thread objects one and two This is what is data sharing..
Multiple threads always share and operate in the same data segment. In other words they share the same process space.
Now the run method of example class tries to call addone method of increment object passed to it.. depending at what time there is a context switch between the threads ( I mean depending on when the OS decide to switch the threads) one and two the final value printed by addone method would vary.
I hope I am clear.
Sasi.