P1-P5: rewrite to match current syllabus

Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
This commit is contained in:
2023-06-05 00:09:49 +05:30
parent 9006831163
commit 539adc94da
7 changed files with 209 additions and 214 deletions

68
P4.java
View File

@@ -1,15 +1,57 @@
class P4 {
public static void main(String[] _args) {
int n = 10;
int a = 0, b = 1;
System.out.println("First " + n + " elements of the fibonacci series:");
new P4().fibo(n, a, b);
}
class ProducerConsumer {
private int limit = 5;
private int tmp = 0;
private int n = 0;
private int m = 0;
void fibo(int n, int a, int b) {
if (n == 0)
return;
System.out.println(a);
fibo(n - 1, b, a + b);
public void produce() throws InterruptedException {
int value = 0;
while (n++ < limit * 2) {
synchronized (this) {
while (tmp == limit) {
wait();
}
System.out.println("Producer produced: " + tmp++);
notify();
}
}
}
}
public void consume() throws InterruptedException {
while (m++ < limit * 2) {
synchronized (this) {
while (tmp == 0) {
wait();
}
System.out.println("Consumer consumed: " + --tmp);
notify();
}
}
}
}
public class P4 {
public static void main(String[] args) {
ProducerConsumer pc = new ProducerConsumer();
Thread producerThread = new Thread(() -> {
try {
pc.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread consumerThread = new Thread(() -> {
try {
pc.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
producerThread.start();
consumerThread.start();
}
}