public class eat extends Thread{
//四部曲:循环,同步代码块,判断共享数据是否到末尾(到),判断共享数据是否到了末尾(未到,则执行核心逻辑)
@Override
public void run() {
while(true){
synchronized(Desk.lock){
if(Desk.mount == 0){
break;
}else{
if(Desk.foodflag == 0){
try {
Desk.lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}else{
Desk.mount--;
System.out.println(getName() + "还能吃" + Desk.mount + "碗");
Desk.lock.notifyAll();
Desk.foodflag = 0;
}
}
}
}
}
}
public class test {
public static void main(String[] args) {
cook c = new cook();
eat e = new eat();
c.setName("厨师");
e.setName("吃货");
c.start();
e.start();
}
public class cook extends Thread{
@Override
public void run() {
while (true){
if (Desk.mount == 0) {
break;
}else {
synchronized(Desk.lock){
if(Desk.foodflag == 0){
System.out.println(getName() + "煮了面");
Desk.foodflag = 1;
Desk.lock.notifyAll();
}else{
try {
Desk.lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
}
public class Desk {
public static int mount = 10;
public static Object lock = new Object();//锁对象
public static int foodflag = 0;
}
阻塞队列:两者必须使用同一个阻塞队列
public class cook extends Thread{
ArrayBlockingQueue<String> queue;
public cook(ArrayBlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
try {
queue.put("面条");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("做了一碗面条");
}
}
}
public class eat extends Thread{
ArrayBlockingQueue<String> queue;
public eat(ArrayBlockingQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
try {
System.out.println(queue.take());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public class test {
public static void main(String[] args) {
ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(1);
cook c = new cook(queue);
eat e = new eat(queue);
c.start();
e.start();
}
}