• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Threading question from Dan's mock

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class A extends Thread {
String[] sa;
public A(String[] sa) {
this.sa = sa; //4
}
public void run() {
System.out.print(sa[0] + sa[1] + sa[2]);
}
}
class B {
public static void main (String[] args) {
String[] sa = new String[]{"X","Y","Z"};
Thread t1 = new A(sa); //1
t1.start(); //3
sa[0] = "A"; //2
sa[1] = "B";
sa[2] = "C";
}
}
I would think that after //1 is executed, array sa (//4) in class A will be initiated with "X", "Y", "Z". And regardless of what is executed next, it will aways print out "XYZ" because the execution of //2 onwards will only change the local variable sa.
Any thoughts?
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Since sa is array. A(sa) pass the refernce of the object to its' member. So both sa in the main and object t1(type A) point to same object.
Hope it helps
 
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
George,
You are correct. Both class A and class B refer to the same object so changes made in the A.run method have an impact in B.main.
Although method A.run can change the contents of the local array, sa, in B.main there is no guarantee that thread t1 will run before B.main runs to completion. For that reason, the actual output of the program can not be predicted with any certainty.
 
Ming Tan
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thank you both for the answers.
 
There's a city wid manhunt for this tiny ad:
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic