Threading and Synchronization in Java

Status
Not open for further replies.
I'm currently working on making the Sun Producer/Consumer example a multi-producer/multi-consumer program. Sun's example can be found here:

http://java.sun.com/docs/books/tutorial/essential/threads/synchronization.html

Basically to make it a multi example I have just looped the starting of the thread(s) in the main.

I have two questions. I want the results to print out like they have on the example.

The first question is that why do I get my results not printed in the correct order? Everything is synchronized but for some reason the results don't printed in the correct order. Why?

code:<HR>
Code:
Producer #1 put: 0
Producer #1 put: 1
Consumer #1 got: 0
Producer #1 put: 2
Consumer #1 got: 1
Consumer #1 got: 2
Producer #2 put: 0
Producer #2 put: 1
Consumer #2 got: 0
Producer #2 put: 2
Consumer #2 got: 1
Consumer #2 got: 2


If you look at the producer code, you see that the thread sleeps for a brief period. Why, when I do this to the multi program does it change the results? If I remove the sleep you see the results above. If I leave it, I get a race condition. Why? The processes are still sychronized in the cubbiehole.

The cubbyhole object looks like this. I didn't see on the sun site.
code:<HR>
Code:
ublic class CubbyHole {
    private int contents;
    private boolean available = false;

    public synchronized int get() {
        while (available == false) {
            try {
                wait();
            } catch (InterruptedException e) { }
        }
        available = false;
        notifyAll();
        return contents;
    }

    public synchronized void put(int value) {
        while (available == true) {
            try {
                wait();
            } catch (InterruptedException e) { }
        }
        contents = value;
        available = true;
        notifyAll();
    }
}


Thanks
 
Status
Not open for further replies.