-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadDemo6.java
More file actions
104 lines (86 loc) · 1.9 KB
/
Copy pathThreadDemo6.java
File metadata and controls
104 lines (86 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package thirdPart;
/**
* @author yangxp
* @date 2017年8月9日 上午9:15:57
* 生产者消费者模式
*/
public class ThreadDemo6 {
public static void main(String[] args) {
String lock = new String("");
Pthread pthread = new Pthread(lock);
Cthread cthread = new Cthread(lock);
ThreadDemo6TestA pThread = new ThreadDemo6TestA(pthread);
ThreadDemo6TestB cThread = new ThreadDemo6TestB(cthread);
pThread.start();
cThread.start();
}
}
class Pthread {
private String lock;
public Pthread(String lock) {
super();
this.lock = lock;
}
public void setValue() {
try {
synchronized (lock) {
if (!ValueObject.value.equals("")) {
lock.wait();
}
ValueObject.value = System.currentTimeMillis() + "_" + System.nanoTime();
System.out.println("Pthread set的值是 : " + ValueObject.value);
lock.notify();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Cthread {
private String lock;
public Cthread(String lock) {
super();
this.lock = lock;
}
public void getValue() {
try {
synchronized (lock) {
if (ValueObject.value.equals("")) {
lock.wait();
}
System.out.println("Cthread get的值是 : " + ValueObject.value);
ValueObject.value = "";
lock.notify();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ValueObject {
public static String value = "";
}
class ThreadDemo6TestA extends Thread {
public Pthread pthread;
public ThreadDemo6TestA(Pthread pthread) {
this.pthread = pthread;
}
@Override
public void run() {
while (true) {
pthread.setValue();
}
}
}
class ThreadDemo6TestB extends Thread {
public Cthread cthread;
public ThreadDemo6TestB(Cthread cthread) {
this.cthread = cthread;
}
@Override
public void run() {
while (true) {
cthread.getValue();
}
}
}