使用synchronized、wait、notify實現的生產者、消費者
public class ProducterAndCustomerVersion1 {
private final static Object LOCK = new Object();
private static boolean isProducted = false;
private static int nums = 0;
/**
* 生產者
*/
public static void producter(){
synchronized (LOCK){
if (!isProducted){
nums++;
isProducted = true;
System.out.println("生產者生產產品:"+nums);
}
LOCK.notify();
try {
LOCK.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 消費者
*/
public static void customer(){
synchronized (LOCK){
if (isProducted){
isProducted = false;
System.out.println("消費者消費產品:"+nums);
}
LOCK.notify();
try {
LOCK.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Test1 {
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(() -> {
while (true){
ProducterAndCustomerVersion1.producter();
}
});
Thread thread2 = new Thread(() -> {
while (true){
ProducterAndCustomerVersion1.customer();
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
}
}