自己写生产者消费者模式,共享lock锁,但是并没起作用
package com.kaber.thread;
import java.util.ArrayList;
import java.util.List;
/**
* @author :Kaber
* @date :2022/7/21 0:34
*/
public class DeadThread {
private static final String lock = "lock";
public static void main(String[] args) {
Integer i = 0;
maker maker = new maker(i, lock);
spender spender = new spender(i, lock);
Thread m = new Thread(maker);
Thread s = new Thread(spender);
m.setName("生产者");
s.setName("消费者");
m.start();
s.start();
}
}
class maker implements Runnable {
private int count;
private String lock;
public maker(int count, String lock) {
this.count = count;
this.lock = lock;
}
@Override
public void run() {
while (true) {
synchronized (lock) {
while (count == 1) {
try {
lock.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
count++;
System.out.println(Thread.currentThread().getName() + ",目前总共有" + count);
lock.notifyAll();
}
}
}
}
class spender implements Runnable{
private int count;
private String lock;
public spender(int count, String lock) {
this.count = count;
this.lock = lock;
}
@Override
public void run() {
while (true) {
synchronized (lock) {
while (count == 0) {
try {
lock.wait();
} catch (Exception e) {
}
}
count--;
System.out.println(Thread.currentThread().getName() + ",目前总共有" + count);
lock.notifyAll();
}
}
}
}
@