Sunday, May 1, 2011

The Cookie Jar Problem

Question: A cookie jar that never becomes empty (the best type!) is being shared by two sisters, Tina and Judy, using the following (not-so-good) rule: Judy can get a cookie from the jar only after Tina (being the older sister) gets a cookie in at least two separate occasions, whereas Tina gets a cookie from the jar whenever she wants to. Treating Tina and Judy as two independently executing processes and the Cookie Jar as a shared resource, develop a concurrent algorithm to solve the Cookie Jar Problem.

Solution:
package cookiejar;

import java.util.Random;

public class CookieJar {

static Object o = new Object();
static int tinaCount = 0;
static Random random = new Random();

public static void main(String... args) {
new Thread(new Tina()).start();
new Thread(new Judy()).start();
}

private static void randomWait() {
int millisecs = random.nextInt(2);
try {
Thread.sleep(millisecs);
} catch (InterruptedException e) {
}
}

static class Tina implements Runnable {

@Override
public void run() {
while (true) {
randomWait();
synchronized (o) {
tinaCount++;
System.out.println("TinaCount = " + tinaCount);
o.notifyAll();
}
System.out.println("Tina is eating cookie.");
}

}

}

static class Judy implements Runnable {

@Override
public void run() {
while (true) {
randomWait();
synchronized (o) {
System.out.println("Judy tries to get a cookie.");
while (tinaCount < 2) {
System.out.println("Judy is waiting since Tina has not eaten 2 times.");
try {
o.wait();
System.out.println("Judy is now awake and again checking for tinaCount.");
} catch (InterruptedException e) {
}
}
}
System.out.println("Judy is eating cookie.");
synchronized (o) {
tinaCount = 0;
System.out.println("Judy has now reset the tinaCount.");
}
}

}

}

}

1 comment:

  1. Pools and fantasy leagues are additionally popular strategies of sports playing. They are largely organized by associates and coworkers, though Internet-based firms increasingly run large-scale variations of these activities. Pools range from predictions of the result result} of 솔 카지노 tournaments or the week’s roster of games to lotteries consisting of numbers that win in the event that they} match a ultimate or partial score.

    ReplyDelete