JAVA多线程编程核心技术-wait/notify[5]
生产者/消费者模式
什么是消费者模式
- 生产者一件产品,通知到消费者去消费这件产品
用wait/notify代码实现
C.java
书中的例子
package com;
public class C {
private String lock;
public C(String lock) {
this.lock = lock;
}
public void getValue() {
try {
synchronized (lock) {
if (ValueObject.value.equals("")) {
lock.wait();
}
System.out.print("get 值" + ValueObject.value+"\n");
ValueObject.value = "";
lock.notify();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
P.java
package com;
public class P {
private String lock;
public P(String lock) {
this.lock = lock;
}
public void setValue() {
try {
synchronized (lock) {
if (!ValueObject.value.equals("")) {
lock.wait();
}
String value = System.currentTimeMillis() + "_" + System.nanoTime();
System.out.println("set的值" + value);
ValueObject.value = value;
lock.notify();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println(System.nanoTime());
System.out.println(System.currentTimeMillis());
}
}
ThreadC.java
package com;
public class ThreadC extends Thread {
private C c;
public ThreadC(C c){
this.c = c;
}
@Override
public void run() {
super.run();
while (true){
c.getValue();
}
}
}
ThreadP.java
package com;
public class ThreadP extends Thread {
private P p;
public ThreadP(P p){
this.p = p;
}
@Override
public void run() {
super.run();
while (true){
p.setValue();
}
}
}
Run.java
package com;
import lombok.val;
public class Run {
public static void main(String[] args) {
val lock = "";
P p = new P(lock);
C c = new C(lock);
ThreadC threadC = new ThreadC(c);
ThreadP threadP = new ThreadP(p);
threadC.start();
threadP.start();
}
}
结果
交替结果运行
get 值1574388799224_9128395605388
set的值1574388799224_9128395628212
get 值1574388799224_9128395628212
set的值1574388799224_9128395651348
get 值1574388799224_9128395651348
set的值1574388799224_9128395668071
get 值1574388799224_9128395668071
多线程假死现象
- 所有线程斗陷入等待,叫做线程假死
原因
因为锁唤醒的并不一定是异类,有可能是同类。唤醒的对象是随机的。
例如:当消费者唤醒某个对象时,唤醒的也可能也是一个消费者,这样会造成程序假死