Java多线程生产者消费者(美团二面笔试)
之前写的生产者消费者模型是用c/c++写的,今天用java写了一个简易的生产者消费者模型,上代码
import java.util.concurrent.locks.*;
public class Main {
public static void main(String[] args) {
Thread p = new Producter(Task.getTask());
Thread c = new Consumer(Task.getTask());
p.start();
c.start();
}
}
class Task {
private Lock lock = new ReentrantLock();
private Condition conditionPro = lock.newCondition();
private Condition conditionCon = lock.newCondition();
private int num;
private static Task task = new Task();
private Task(){ num = 0; }
public static Task getTask(){
return task;
}
public void consume(){
while(true){
lock.lock();
try {
if(num == 0){
conditionCon.await();
}
System.out.println("consume the number" + num);
num--;
conditionPro.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
lock.unlock();
}
}
}
public void product(){
while(true){
lock.lock();
try {
if(num == 1){
conditionPro.await();
}
System.out.println("product the number" + num);
num++;
conditionCon.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
lock.unlock();
}
}
}
}
class Producter extends Thread{
private Task task;
public Producter(Task task){
this.task = task;
}
@Override
public void run(){
task.product();
}
}
class Consumer extends Thread{
private Task task;
public Consumer(Task task){
this.task = task;
}
@Override
public void run(){
task.consume();
}
}