本篇文章來自本人實踐,生產者和消費者問題在面試中也是經常被問及到,上代碼
package com.ruider.currentTest;
public class ProducerAndConsumer {
private static Resource resource = new Resource();
public static void main (String[] args) throws InterruptedException{
ProducerAndConsumer producerAndConsumer = new ProducerAndConsumer();
Consumer consumer1 = new Consumer(producerAndConsumer.resource);
Producer producer1 = new Producer(producerAndConsumer.resource);
Thread consumer = new Thread(consumer1,"consumer");
Thread producer = new Thread(producer1,"producer");
producer.start();
consumer.start();
//主線程等待1秒,使生產者和消費者兩個線程執行
Thread.sleep(1000);
}
//資源類
public static class Resource {
//先生產後消費
private volatile boolean flag = false;
public boolean getFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
//消費者
public static class Consumer implements Runnable {
private Resource resource;
public Consumer(Resource resource) {
this.resource = resource;
}
@Override
public void run () {
synchronized (resource) {
while(true) {
try{
if(!resource.getFlag()) {
resource.wait();
}
System.out.println("消費者---------消費");
Thread.sleep(1000);
resource.setFlag(false);
resource.notify();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
//生產者
public static class Producer implements Runnable {
private Resource resource;
public Producer(Resource resource) {
this.resource = resource;
}
@Override
public void run () {
synchronized (resource) {
//獲取到鎖之後循環獲取資源
while(true) {
try{
if(resource.getFlag()) {
resource.wait();
}
System.out.println("生產者---------生產");
Thread.sleep(1000);
resource.setFlag(true);
resource.notify();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}