-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjavalab20.java
More file actions
83 lines (69 loc) · 2.42 KB
/
Copy pathjavalab20.java
File metadata and controls
83 lines (69 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import java.util.*;
class ProducerConsumer extends Thread{
LinkedList<Integer> buffer = new LinkedList<>();
Scanner sc = new Scanner(System.in);
int capacity=5;
int value=1;
public synchronized void produce() {
try {
if (buffer.size() == capacity) {
System.out.println("Buffer full. Producer is waiting...");
wait(); // Producer waits if buffer full
}
for (int i = 0; i < capacity; i++) {
System.out.println("Producer produced: " + value);
buffer.add(value++);
Thread.sleep(500);
}
System.out.println();
notify(); // Wake up consumer
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void consume() {
try {
if (buffer.size() == 0) {
System.out.println("Buffer empty. Consumer is waiting...");
wait(); // Consumer waits if buffer empty
}
for(int i=0; i< capacity; i++){
int value = buffer.removeFirst();
System.out.println("Consumer consumed: " + value);
Thread.sleep(500);
}
notify(); // Wake up producer
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
/*.printStackTrace() is a method that prints the full error details to your console.
It shows where the exception happened, including:
the exact line number,
class name,
method call hierarchy.*/
}
}
}
public class javalab20 {
public static void main(String [] args) {
ProducerConsumer ob = new ProducerConsumer();
Scanner sc = new Scanner(System.in);
System.out.print("Enter how many times you want to do the process: ");
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.println();
System.out.println();
System.out.println("Process " + (i + 1));
System.out.println();
ob.produce();
ob.consume();
try {
Thread.sleep(1000); // Sleep after each cycle
} catch (InterruptedException e) {
e.printStackTrace();
}
}
sc.close();
}
}