package test;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test{
static Scanner sc = new Scanner(System.in);
static String line;
static class Food{
static int id = 0;
private int mid = id++;
public Food() {
}
@Override
public String toString() {
return "食物id="+mid;
}
}
static Food f = null;
static class Producer implements Runnable{
@Override
public void run() {
while(!Thread.interrupted()){
synchronized (this) {//等待过程,对应消费过程,所以应该上锁
while(f!=null){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("生产");
synchronized (c) {
f = new Food();
c.notifyAll();
}
}
}
}
static class Comsumer implements Runnable{
@Override
public void run() {
while(!Thread.interrupted()){
synchronized (this) {
while(f==null){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("消费"+f);
synchronized (p) {
f = null;
p.notifyAll();
}
}
}
}
static Producer p = new Producer();
static Comsumer c = new Comsumer();
public static void main(String[] args) {
ExecutorService exe = Executors.newCachedThreadPool();
exe.execute(p);
exe.execute(c);
}
}
java实现线程同步一个生产者和一个消费者
最新推荐文章于 2021-08-27 16:30:17 发布