-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTest.java
More file actions
85 lines (75 loc) · 1.9 KB
/
Copy pathTest.java
File metadata and controls
85 lines (75 loc) · 1.9 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
84
85
class Test {
public static void main(String[] args) {
Resourse resourse = new Resourse();
Thread p = new Producer("P", resourse);
Thread c = new Thread(new Consumer("C", resourse));
p.start();
try {
Thread.sleep(1000);
} catch (Exception e) {
System.out.println(e);
}
c.start();
}
}
class Resourse {
Boolean isproduced = false;
int data;
synchronized void put(int x) throws Exception {
if (isproduced) {
wait();
}
this.data = x;
isproduced = true;
notifyAll();
}
synchronized int get() throws Exception {
if (!isproduced) {
wait();
}
isproduced = false;
notifyAll();
return data;
}
}
class Producer extends Thread {
String name;
Resourse res;
Producer(String name, Resourse res) {
this.name = name;
this.res = res;
}
public void run() // not mandatory
{
try {
for (int i = 0; i < 10; i++) {
res.put(i);
System.out.println("Produced = " + i);
Thread.sleep(1000);
}
} catch (Exception e) {
} finally {
System.out.println("Producer finished the job.");
}
}
}
class Consumer implements Runnable {
String name;
Resourse res;
Consumer(String name, Resourse res) {
this.name = name;
this.res = res;
}
public void run() // Mandatory
{
try {
for (int i = 0; i < 10; i++) {
System.out.println("Consumed = " + res.get());
Thread.sleep(1000);
}
} catch (Exception e) {
} finally {
System.out.println("Consumer finished the job.");
}
}
}