Hi Everyone,
I'am currently working on this question:
Write a producer-consumer problem that uses threads and shares a common buffer. However do not use semaphores or any other synchronization primitives to guard the shared data structures. Just let each thread access them when it wants to. Use sleep and wakeup to handle the full and empty conditions. See how long it takes for a fatal race condition to occur. For example you might have the producer print a number once in a while. Do not print that number every minute because the I/O could affect the race conditions.
This is what I managed to do:
import java.nio.*;
public class Buffer {
private int buffer = -1;
public void set(int val)
{
System.out.println("Writing" + val);
buffer = val;
}
public int get()
{
System.out.println("Reading" + buffer);
return buffer;
}
}
import java.lang.*;
import java.nio.*;
public class Consumer extends Thread implements Runnable{
private Buffer sharedBuf; // the buffer is the same buffer used by the producer
int sum = 0; // total stuff read from the buffer
//..constructor should accept(Buffer), and set it to the sharedBuf ...
public Consumer (Buffer sharedBuf){
this.sharedBuf=sharedBuf;
}
public void threadRun() throws InterruptedException {
try{
// read the buffer four times, and keep the total
for (int i=1; i<=4; i++)
{
sleep(1);
sum = sum + sharedBuf.get();
}
}
catch(InterruptedException exception) {
exception.printStackTrace();
}
System.out.println("Consumer finished, ate " + sum + "exiting...");
}
}
import java.lang.*;
import java.nio.*;
public class Producer extends Thread implements Runnable{
private Buffer sharedBuf; // the buffer is the buffer class above
// constructor should accept (Buffer), and set it to the sharedBuf ...
public Producer (Buffer sharedBuf){
this.sharedBuf=sharedBuf;
}
public void threadRun()throws InterruptedException
{
try{
for (int i=1; i<=4; i++)
{
sleep(1);//sleep for a random time, between 0-3 seconds for example;
sharedBuf.set(i);
}
}
catch (InterruptedException exception) {
exception.printStackTrace();
}
System.out.println("Producer finished, exiting...");
}
}
public class test {
public static void main(String args[]) {
Buffer shared = new Buffer();
Thread a=new Thread( new Producer(shared));
a.start();
Thread b=new Thread( new Consumer(shared));
b.start();
}
}
My problem is that I cant get my program to give me a output, and i dont know where im supposed to put my wakeup statements....
Thanks for your help in advance,
itchap