Results 1 to 3 of 3
- 09-09-2008, 01:49 PM #1
Member
- Join Date
- Sep 2008
- Posts
- 1
- Rep Power
- 0
synchronization kid riding a swing n catching breath
Hi java gurus im a newbie in jave have a problem with my java synchronized methods.. the output should be like this
Alice: I want to ride the swing
Alice: I get to ride the swing for 5940 ms
Bob: I want to ride the swing
Charlie: I want to ride the swing
Alice: Im tired pausing for 4440 ms
Bob: I get to ride the swing for 4231 ms
Alice: I want to ride the swing
Bob: Im tired pausing for 6934 ms
Charlie: I get to ride the swing for 4204 ms
....
this is my code.. any help would be greatly appreciated. Thanks! :)
class MyRideSwing {
public void rideswing(String name) {
int mydelay = (int)(Math.random() * 5000);
System.out.println(name + ": want");
synchronized(this) {
System.out.println(name + ": I get to ride the swing for " + mydelay +" milleseconds");
try {
Thread.sleep(mydelay);
}catch (InterruptedException e){}
this.breathe(name);
}
}
public void breathe(String name) {
int mydelay = (int)(Math.random() * 5000);
System.out.println(name + ": tired" + mydelay +" milleseconds");
try {
Thread.sleep(mydelay);
}catch (InterruptedException e){}
}
}
class Kid extends Thread {
String name;
MyRideSwing p;
Kid(String name, MyRideSwing p) {
this.name = name; this.p = p;
}
public void run() {
for (int ctr=0; ctr < 500; ctr++) {
p.rideswing(name);
}
}
}
class RideASwing {
public static void main(String args[]){
MyRideSwing p = new MyRideSwing();
Kid k1 = new Kid("Alice",p);
Kid k2 = new Kid("Bob",p);
Kid k3 = new Kid("Charlie",p);
k1.start();
k2.start();
k3.start();
}
}
- 09-10-2008, 01:03 PM #2
Member
- Join Date
- Sep 2008
- Posts
- 17
- Rep Power
- 0
hello
when u r create more than one thread and start it ,you cannot say that threads run in specific manner,JVM run thread with thread priority and scheduling algorithm which platform dependant.
Hence order in which u want to print output is not possible
RegardsSagar Birari
Development & Technical Blog
- 09-10-2008, 01:46 PM #3
Similar Threads
-
Over-riding purpose fails..
By udayadas in forum New To JavaReplies: 7Last Post: 08-24-2008, 04:14 AM -
Animation Synchronization
By dreadrocksean in forum Advanced JavaReplies: 5Last Post: 08-08-2008, 02:56 AM -
synchronization question
By oguz in forum Threads and SynchronizationReplies: 2Last Post: 07-22-2008, 08:56 AM -
Swing - catching click button event
By Java Tip in forum Java TipReplies: 0Last Post: 03-11-2008, 11:03 PM -
AWT - catching click button event
By Java Tip in forum Java TipReplies: 0Last Post: 03-11-2008, 11:02 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks