生產者和消費者問題
生產者和消費者的問題是一個執行緒通信的例子,
比如買饅頭,需要先進行生產,生產了就通知消費者來吃饅頭,如果饅頭沒了就通知生產者繼續生產,
public class Test {
public static void main(String[] args) {
Click click = new Click(0);
new Thread(new Productor(click),"生產").start();
new Thread(new Consumer(click),"消費").start();
}
}
//生產者
class Productor implements Runnable{
private Click click;
Productor(Click click){
this.click = click;
}
@Override
public void run() {
while (true){
synchronized (click) {
if (click.num < 10) {
click.num++;
System.out.println(Thread.currentThread().getName() + "第:" + click.num + "個商品");
click.notify();
} else {
try {
click.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
//消費者
class Consumer implements Runnable{
private Click click;
Consumer(Click click){
this.click = click;
}
@Override
public void run() {
while (true) {
synchronized (click) {
if (click.num > 0) {
System.out.println(Thread.currentThread().getName() + "第:" + click.num + "個商品");
click.num--;
click.notify();
} else {
try {
click.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
//饅頭店
class Click{
int num;
Click(int num){
this.num = num;
}
}
運行結果:

這里需要注意synchronized的鎖物件應該是饅頭店,不能是this,因為饅頭店只有一個,而this指當前物件,生產者和消費者都創建了,所以使用this不行,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/194140.html
標籤:Java
