ProConUnprotected: Initial commit

This commit is contained in:
2025-03-19 20:42:54 +01:00
parent 519152a7b9
commit 717dd7835e
9 changed files with 121 additions and 0 deletions

View File

@@ -0,0 +1,5 @@
public interface Buffer {
public void set( int va1ue ); // place value into Buffer
public int get(); // return value from Buffer
}

View File

@@ -0,0 +1,24 @@
public class Consumer extends Thread {
private Buffer sharedLocation;
public Consumer( Buffer shared ) {
super("Consumer");
sharedLocation = shared;
}
public void run() {
int sum = 0;
for (int count = 1; count <= 4; count++) {
try {
Thread.sleep((int)(Math.random() * 3001));
sum += sharedLocation.get();
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
}
System.err.println( getName() + " read values totalling: " + sum + " ...DONE");
}
}

View File

@@ -0,0 +1,22 @@
public class Producer extends Thread {
private Buffer sharedLocation;
public Producer( Buffer shared ) {
super("Producer");
sharedLocation = shared;
}
public void run() {
for (int count = 1; count <= 4; count++) {
try {
Thread.sleep((int)(Math.random() * 3001));
sharedLocation.set(count);
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
}
System.err.println( getName() + " done producing.");
}
}

View File

@@ -0,0 +1,15 @@
public class SharedBufferTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Buffer sharedLocation = new UnsynchronizedBuffer();
Producer producer = new Producer( sharedLocation);
Consumer consumer = new Consumer( sharedLocation);
producer.start();
consumer.start();
}
}

View File

@@ -0,0 +1,15 @@
public class UnsynchronizedBuffer implements Buffer {
private int buffer = -1;
public void set( int value ) {
System.err.println( Thread.currentThread().getName() + " writes " + value);
buffer = value;
}
public int get() {
System.err.println( Thread.currentThread().getName() + " reads " + buffer);
return buffer;
}
}