// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;

public class ThreadFun {
    private static Random rng = new Random();
    public static void main(String[] args) throws Exception {
        SynchronousQueue<String> sq1 = new SynchronousQueue<String>();
        SynchronousQueue<String> sq2 = new SynchronousQueue<String>();
        NotFound t1 = new NotFound(sq1, sq2);
        t1.start();
        Semaphore fnd = new Semaphore(1);
        fnd.acquire();
        Found t2 = new Found(fnd);
        t2.start();
        while(rng.nextInt(100) != 50){
            System.out.println("In loop");
            sq1.put("go");
            sq2.take();
        }
        t1.setDone();
        fnd.release();
        t1.interrupt();
        t1.join();
        t2.join();
    }
}

class NotFound extends Thread {
    private SynchronousQueue<String> sq1;
    private SynchronousQueue<String> sq2;
    private volatile boolean done;
    public NotFound(SynchronousQueue<String> sq1, SynchronousQueue<String> sq2) {
        this.sq1 = sq1;
        this.sq2 = sq2;
        this.done = false;
    }
    public void run() {
            try {
                while(!done) {
                    sq1.take();
                    System.out.println("Ikke fundet!");
                    sq2.put("go");
                }
            } catch (InterruptedException e) {
            }
    }
    public void setDone() {
        done = true;
    }
}

class Found extends Thread {
    private Semaphore fnd;
    public Found(Semaphore fnd) {
        this.fnd = fnd;
    }
    public void run() {
            try {
                fnd.acquire();
                System.out.println("Fundet!");
            } catch (InterruptedException e) {
            }
    }
}
