Thread: Thread waiting.
View Single Post
Old Mar 6th, 2008, 7:42 AM   #1
equinox
Newbie
 
Join Date: Nov 2007
Posts: 8
Rep Power: 0 equinox is on a distinguished road
Thread waiting.

I'm having a problem making threads wait on one another. What I'm doing is just a very simple program that has two classes, one that takes "sweets" from a bag called the child and another that puts them in called the parent. Now I'm using a boolean to control when they should each wait and that works fine.

The trouble is, I can't get them to restart. The sun toutorial says that notify() and notiftAll() will wake up a method that is allready waiting but they just dont' seem to do anything . The two classes are shown below.

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 synchronized void run() 
	{

		while (true) 
		{
			while(bag.avail)
			{
				try
				{
					System.out.println("Parent is waiting...");
					wait();
				}
				catch (InterruptedException e)
				{
				}
			}

			

			bag.sweets++;
			bag.in++;
			bag.avail = true; //change avail to true so that the child won't have to  wait
			notify();

			System.out.println("parent puts in: " + bag.in + " sweets is now = " + bag.sweets);
			
		}

	}
}

// 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 synchronized void run() 
	{

		while (true) 
		{
			while(!bag.avail) 
			{
				try
				{
					System.out.println("Child is waiting...");
					wait();
				}
				catch (InterruptedException e)
				{
				}
			}
			//System.out.println("child takes out: " + bag.out + " sweets is now = " + bag.sweets);

			bag.sweets--;
			bag.out++;
			bag.avail = false; //change to false so the parent need not wait
			
			notify(); //here's the problem
			

			
		}
	
	}
}


The variables are all in a seperate class called bag. I can get this to work using "busy waiting", by making the threads loop rather than wait. I'm really stuck with this one and I just need a push in the right direction. Thanks all.
equinox is offline   Reply With Quote