-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLab8_1.java
More file actions
66 lines (59 loc) · 1.33 KB
/
Lab8_1.java
File metadata and controls
66 lines (59 loc) · 1.33 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
import java.util.*;
import java.io.*;
class Q {
int num;
boolean valueSet = false;
public synchronized void put(int num) {
while(valueSet) {
try { wait(); } catch(Exception e) {}
}
System.out.println("Put: " + num);
this.num = num;
valueSet = true;
notify();
}
public synchronized void get() {
while(!valueSet) {
try { wait(); } catch(Exception e) {}
}
System.out.println("Get: " + num);
valueSet = false;
notify();
}
}
class Producer implements Runnable {
Q q;
public Producer(Q q) {
this.q = q;
Thread t = new Thread(this, "Producer");
t.start();
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
try { Thread.sleep(1000); } catch(Exception e) {}
}
}
}
class Consumer implements Runnable {
Q q;
public Consumer(Q q) {
this.q = q;
Thread t = new Thread(this, "Consumer");
t.start();
}
public void run() {
while(true) {
q.get();
try { Thread.sleep(1000); } catch(Exception e) {}
}
}
}
public class Lab8_1 {
public static void main(String[] args) {
Q q = new Q();
new Producer(q);
new Consumer(q);
}
}