Hi all, I am having a problem with the synchronizing the threads in the classic produce consume thread example. Below is my code for it.
public class Magpie extends Thread {
private TreeHole treehole;
private int number;
public Magpie(TreeHole t, int number) {
treehole = t;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 5; i++) {
value = treehole.get();
System.out.println("Magpie " + this.number + " got: " + value);
}
}
}
class Squirrel extends Thread {
private TreeHole treehole;
private int number;
public Squirrel(TreeHole t, int number) {
treehole = t;
this.number = number;
}
public void run() {
for (int i = 0; i < 5; i++) {
treehole.put(i);
System.out.println("Squirrel " + this.number + " put: " + i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) {
}
}
}
}//end class
//import java.util.concurrent.Executors;
//import java.util.concurrent.ExecutorService;
public class SquirrelMagpieTest {
public static void main(String[] args) {
TreeHole t = new TreeHole();
Squirrel s1 = new Squirrel(t, 1);
Magpie t1 = new Magpie(t, 1);
//ExecutorService threadExecutor = Executors.newCachedThreadPool();
//threadExecutor.execute (t1);
//threadExecutor.execute (s1);
s1.start();
t1.start();
}
}
class TreeHole
{
private int seq;
private boolean available = false;
public synchronized int get()
{
while (available == false)
{
try {
wait();
} catch (InterruptedException e) {
}
}
available = false;
notifyAll();
return seq;
}
public synchronized void put(int value)
{
while (available == true)
{
try {
wait();
} catch (InterruptedException e) {
}
}
seq = value;
available = true;
notifyAll();
}
}
I am having trouble synchronizing the threads and this is evident when sometimes the output will work fine with the magpie taking the int after the squirrel but then sometimes it will take the int before the squirrell has had a chance of putting the new int into the treehole value. I am also looking at extended this to increase N and M number of squirrels and magpies specified by a user, any suggestions on this would also be greatly apprectiated.
Cheers to all.