added ex D

This commit is contained in:
Louis Heredero 2024-12-09 15:41:08 +01:00
parent 104df9d3f8
commit 790c1ffea0
Signed by: HEL
GPG Key ID: 8D83DE470F8544E7
3 changed files with 72 additions and 0 deletions

View File

@ -0,0 +1,23 @@
package exercicses.ex_d;
import java.util.Stack;
public class EmptyingThread extends Thread {
private Stack<Integer> source;
private Stack<Integer> target;
public EmptyingThread(Stack<Integer> source, Stack<Integer> target) {
this.source = source;
this.target = target;
}
@Override
public void run() {
int v;
while (!source.isEmpty()) {
v = source.pop();
System.out.println("Number popped from source stack and pushed to target stack: " + v);
target.push(v);
}
}
}

View File

@ -0,0 +1,31 @@
package exercicses.ex_d;
import java.util.Stack;
public class FillingThread extends Thread {
private Stack<Integer> source;
private Stack<Integer> target;
private Thread emptyingThread;
public FillingThread(Stack<Integer> source, Stack<Integer> target, Thread emptyingThread) {
this.source = source;
this.target = target;
this.emptyingThread = emptyingThread;
}
@Override
public void run() {
try {
emptyingThread.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("--- Starting Filling back ---");
int v;
while (!target.isEmpty()) {
v = target.pop();
System.out.println("From target stack to source stack " + v);
source.push(v);
}
}
}

View File

@ -0,0 +1,18 @@
package exercicses.ex_d;
import java.util.Stack;
public class TestingJoins {
public static void main(String[] args) {
Stack<Integer> sourceStack = new Stack<Integer>();
Stack<Integer> targetStack = new Stack<Integer>();
// Populating the first sourceStack
for (int i = 1; i <= 10; i++) {
sourceStack.push(i);
}
Thread emptyingThread = new EmptyingThread(sourceStack, targetStack);
Thread fillingThread = new FillingThread(sourceStack, targetStack, emptyingThread);
emptyingThread.start();
fillingThread.start();
}
}