CircularBuffer: Nice buffer with lambda producer and consumer

This commit is contained in:
Karsten Jeppesen
2021-03-02 17:20:41 +01:00
parent d363a3e30a
commit ba6d58efb9
4 changed files with 96 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>
</classpath>

17
CircularBuffer/.project Normal file
View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>CircularBuffer</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,48 @@
// All non primary objects (int, char etc) have wait, notify, notifyAll
// Methods "synchronized" to provide intrinsic locks
// If a thread calling wait() method does not own the inherent lock,
// an error will be thrown.
public class Buffer {
private int BufferSize = 4;
private int[] Container = new int[BufferSize];
private int PosR=0, PosW=0;
public synchronized int Read() {
while (true) {
if ( PosR == PosW ) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
int v=Container[ PosR ];
PosR = (PosR+1) % BufferSize;
System.out.println("Read pos " + PosR);
notifyAll();
return v;
}
}
}
public synchronized void Write( int Val ) {
while (true) {
if (((PosW + 1) % BufferSize) == PosR) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Container[PosW] = Val;
PosW = (PosW+1) % BufferSize;
System.out.println("Write pos " + PosW);
notifyAll();
return;
}
}
}
}

View File

@@ -0,0 +1,25 @@
public class CircularBuffer {
static Buffer MyBuffer = new Buffer();
public static void main(String[] args) {
// TODO Auto-generated method stub
new Thread(() -> {
System.out.println("Producer running");
for ( int nn=0; nn < 20; nn++) {
MyBuffer.Write( nn );
System.out.println("Producer Wrote " + nn);
}
}).start();
new Thread(() -> {
System.out.println("Consumer running");
for ( int nn=0; nn < 20; nn++ ) {
System.out.println("Consumer Read " + MyBuffer.Read());
}
}).start();
}
}