1. 对多线程的一点理解
多线程之间的竞争实际上是对公共资源的一个竞争,在竞争这个资源的时候,我们需要保护好这个公共资源。所以才对竞争的地方进行加锁操作。
2. 基于synchronize + wait + notifyAll的代码实现
/**
* 生产者消费者模式:利用synchronize、wait、notifyAll
*
* @date 2021/12/8 17:03
*/
public class Resource {
public static void main(String[] args) {
Resource resource = new Resource();
Producer producer = new Producer(resource);
Consumer consumer = new Consumer(resource);
new Thread(producer).start();
new Thread(consumer).start();
}
private int num = 0;
public synchronized void produce() {
// condition does not hold
while (num >= 10) {
try {
System.out.println("当前生产者 < " + Thread.currentThread().getName() + " > 进入等待");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num++;
System.out.println("生产者 - < " + Thread.currentThread().getName() + " >, 当前资源数量为:" + num);
// 生产完数据后,唤醒等待的消费线程消费数据
this.notifyAll();
}
public synchronized void consume() {
while (num <= 0) {
try {
System.out.println("当前消费者 < " + Thread.currentThread().getName() + " > 进入等待");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num--;
System.out.println("消费者 - < " + Thread.currentThread().getName() + " >, 当前资源数量为:" + num);
// 消费完数据,唤醒等待的生产线程生产数据
this.notifyAll();
}
}
class Producer implements Runnable {
Resource resource;
public Producer(Resource resource) {
this.resource = resource;
}
@Override
public void run() {
while (true) {
resource.produce();
}
}
}
class Consumer implements Runnable {
Resource resource;
public Consumer(Resource resource) {
this.resource = resource;
}
@Override
public void run() {
while (true) {
resource.consume();
}
}
}
网友评论