-
Threading problem
Hi there
Working through Sierra & Bates for the SCJP, and stuck on one of the excercises. I think I'm missing something obvious here:
I want three threads to modify my StringBuffer object so the result should be the letter A 100 times, B 100 times and C 100 times without interfering with eachother. I can't get the iteration to work though. Does anyone have any tips? Thanks so much! Andy
class JenkSynch extends Thread{
JenkSynch(StringBuffer y){}
public void run(){
synchronized (y){
if (JenkSynch.currentThread().getName() == "Gavin")
{y.append("B");
y.delete(0,1);}
if (JenkSynch.currentThread().getName() == "Howard")
{y.append("C");
y.delete(0,1);}
for (int x = 0; x<100; x++) {
System.out.print (y);}
}
}
public static void main(String[] args){
JenkSynch Sam = new JenkSynch(y);
JenkSynch Gav = new JenkSynch(y);
JenkSynch How = new JenkSynch(y);
Gav.setName("Gavin");
How.setName("Howard");
Sam.start();
Gav.start();
How.start();
}
static StringBuffer y = new StringBuffer("A");
}
-
Apologies, here it is again with code tags:
Code:
class JenkSynch extends Thread{
JenkSynch(StringBuffer y){}
public void run(){
synchronized (y){
if (JenkSynch.currentThread().getName() == "Gavin")
{y.append("B");
y.delete(0,1);}
if (JenkSynch.currentThread().getName() == "Howard")
{y.append("C");
y.delete(0,1);}
for (int x = 0; x<100; x++) {
System.out.print (y);}
}
}
public static void main(String[] args){
JenkSynch Sam = new JenkSynch(y);
JenkSynch Gav = new JenkSynch(y);
JenkSynch How = new JenkSynch(y);
Gav.setName("Gavin");
How.setName("Howard");
Sam.start();
Gav.start();
How.start();
}
static StringBuffer y = new StringBuffer("A");
}
-
Before worrying about threading issues, you will want to tackle using == with reference variables such as Strings. Much better is to use the equals or equalsIgnoreCase method or as you don't really care if one String variable refers to the same String object as another but rather whether they contain the same characters sequences.
-
Ah you legend. That's sorted it. Thanks very much!