i have a code and want to make threads to work mutually,without using semaphores,just key words(wait,notify).this code implements four classes: Bag, Parent, Child and Sweets. Sweets creates an instance of Bag which is shared by the two threads, Parent and Child. The Parent continuously puts sweets into the bag while the Child continuously takes sweets out of the bag. As it stands the code will run but produces some rather strange results. One might expect the number of sweets in the bag to always equal the number put in minus the number taken out, i.e., the following should hold:
sweets = in - out, or,
delta = in - out - sweets = 0
Currently the code prints out the value of delta every two seconds. It does not remain zero.
// The bag that holds the sweets
class Bag {
// Variables
public int sweets, in, out;
// Constructor
public Bag() {
sweets = in = out = 0;
}
}
// The parent thread
class Parent extends Thread {
// Our thread works on this
public Bag bag;
// Constructor
public Parent(Bag bag) {
this.bag = bag;
}
// What our thread does
public void run() {
while (true) {
bag.sweets++;
bag.in++;
}
}
}
// The child thread
class Child extends Thread {
// Our thread works on this
public Bag bag;
// Constructor
public Child(Bag bag) {
this.bag = bag;
}
// What our thread does
public void run() {
while (true) {
bag.sweets--;
bag.out++;
}
}
}
// Main
class Sweets {
public static void main(String[] args) throws InterruptedException {
// Create our bag
Bag bag = new Bag();
// Create our child thread
Child cthread = new Child(bag);
// Create our parent thread
Parent pthread = new Parent(bag);
// Start threads
cthread.start();
pthread.start();
// Keep track
while (true) {
// Sleep for two seconds
Thread.sleep(2000);
// Display the current state of affairs
System.out.println("Delta = " + (bag.in - bag.out - bag.sweets)
+ " Sweets = " + bag.sweets);
}
}
}


LinkBack URL
About LinkBacks




Reply With Quote

Bookmarks
Algorithms and Data Structures
Java tutorials
Algorithms Forum