hi folks! check out the following code'output. why this is not printing this first second third third third third if thread t3 starts its execution in the end it should overwrite the string by "third" n so keep printing "third". class thread implements Runnable { String s; Thread t1; Thread t2; Thread t3; thread() { t1 = new Thread(this,"first"); t2 = new Thread(this,"second"); t3 = new Thread(this,"third"); t1.start(); t2.start(); t3.start(); } public void run() { s = Thread.currentThread().getName(); for(int i=0;i<3;i++) System.out.println(s); } public static void main(String args[]) { new thread(); } }
output:- first second third first second third first second third
Napa Sreedhar
Ranch Hand
Joined: Jan 29, 2002
Posts: 58
posted
0
Thread is a seperate path of execution and each thread has its own stack. The output produced depended on the scheduling policy Roun-robin of your OS. You can better sychronize and program your threads for better results. Napa
reehan ishaque
Ranch Hand
Joined: Mar 25, 2001
Posts: 54
posted
0
thanks napa! But 1 thing i don understand that there is only 1 copy of String s, so it should contain the value that is written by the thread starting in the end n so keep on printing the name of that thread? Does it mean each thread keeps its own copy of objetc's instance variable on which the thread is running?
Shanmukha Rewal
Greenhorn
Joined: Jan 05, 2002
Posts: 1
posted
0
I got the following answer: first first first second second second third third third I ran it on Windows machine. So it's a time sliced. Shanmukha
Peter Chase
Ranch Hand
Joined: Oct 30, 2001
Posts: 1970
posted
0
Originally posted by reehan ishaque: But 1 thing i don understand that there is only 1 copy of String s, so it should contain the value that is written by the thread starting in the end n so keep on printing the name of that thread? Does it mean each thread keeps its own copy of objetc's instance variable on which the thread is running?
Generally, no, each thread does not keep its own copy of instance variables. However, it is not guaranteed that every change to an instance variable will be written straight away to main memory; for performance, it may be kept in something akin to a processor register. I suspect that this may be happening with your String instance variable "s". Otherwise, as you say, the output that you see would not be possible. You can instruct that a variable should always be written straight away to main memory by declaring it "volatile". Try that and see if you get the result you were expecting. Note: all this stuff is instructive but, as a previous respondent said, in a real program you would use synchronisation to ensure thread safety.
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.<br /> <br />#:^P