Java Swing Layout Manager Event Handling Inner Classes Swing Applet Exceptions Threads![]() Multitasking & Multithreading![]() What is a Thread![]() Sequential Flow of Control![]() Life Cycle of a Thread![]() Subclassing Thread![]() Controlling Thread![]() Implementating Runnable![]() When to Use the Runnable Interface![]() Multithreading Example![]() Pre-emptive Scheduling![]() Synchronization (Consumer/Producer)![]() The Producer![]() The Consumer![]() Testing![]() Mutual Exclusion ![]() Exercise![]() Deadlock Java I/O Network Programming Resources | Synchronization (Consumer/Producer)The MessageBuffer class, a shareable Java object. The general solution is to give methods mutually exclusive access to shared objects. Multual exclusion can be modeled as atomic actions. ![]() import java.util.Random;
/**
* @author jack
*/
public class MessageBuffer {
private int[] buffer;
private int size;
private int head;
private int tail;
private int count;
private int writers = 0;
private Random random = new Random();
MessageBuffer(int size) {
this.size = size;
buffer = new int[size];
head = tail = count = 0;
}
public void randomYield() {
if (random.nextBoolean())
Thread.currentThread().yield();
}
public void put(int i) {
while (count >= size) //buffer is full
waitForNotification();
count++;
notifyOthers();
randomYield(); //artificial processing delay
buffer[head] = i;
head++;
if (head >= size)
head = 0;
}
public int get() {
while (count == 0 && writers > 0)
waitForNotification(); //only if there is writer
if (count == 0 && writers <= 0)
return -1;
int i = buffer[tail];
count--;
tail++;
if (tail >= size)
tail = 0;
notifyOthers();
randomYield(); //artificial processing delay
return i;
}
public void registerWriter() {
writers++;
}
public void unregisterWriter() {
writers--;
notifyOthers();
}
private void waitForNotification() {
synchronized (this) {
try {
wait(); //required to be in a synchronized block
} catch (InterruptedException e) {
}
}
}
private void notifyOthers() {
synchronized(this) {
notifyAll();
}
}
}
|