Results 1 to 4 of 4
Thread: Threading problem
- 12-05-2010, 08:32 PM #1
Member
- Join Date
- Oct 2009
- Posts
- 10
- Rep Power
- 0
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");
}
- 12-05-2010, 08:44 PM #2
Member
- Join Date
- Oct 2009
- Posts
- 10
- Rep Power
- 0
Apologies, here it is again with code tags:
Java 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.
- 12-05-2010, 09:27 PM #4
Member
- Join Date
- Oct 2009
- Posts
- 10
- Rep Power
- 0
Similar Threads
-
Problem in Multi threading.
By Chetans in forum Advanced JavaReplies: 3Last Post: 03-23-2010, 04:42 PM -
Getting problem in threading in JAVA
By Chetans in forum Threads and SynchronizationReplies: 3Last Post: 03-19-2010, 07:49 AM -
need some help with threading
By dinosoep in forum New To JavaReplies: 3Last Post: 12-03-2009, 05:31 PM -
Threading
By jon80 in forum New To JavaReplies: 1Last Post: 06-13-2009, 10:53 PM -
Problem in threading
By saurabh in forum Threads and SynchronizationReplies: 6Last Post: 12-01-2008, 08:16 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks