##消費者和生產者(一)
在多線程中,生產者和消費者是一個比較經典的話題,
單消費者單生產者
直接貼代碼(依賴lombok)
生產者代碼:
@AllArgsConstructor
@Data
public class Producter extends Thread{
private Resources resources;
@Override
public void run() {
while (true){
resources.set("Iphone 9");
}
}
}
消費者代碼
@AllArgsConstructor
@Data
public class Consumer extends Thread{
private Resources resources;
@Override
public void run() {
while (true){
resources.out();
}
}
}
資源類代碼:
@Data
public class Resources {
private String name;
private int id =1;
private boolean hasGoods = false;
//生產方法
public synchronized void set(String name) {
if(hasGoods){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name+"-----"+id;
id++;
System.out.println("生產線程名稱:"+Thread.currentThread().getName()+",生產商品爲"+this.name);
hasGoods = true;
notify();
}
//消費方法
public synchronized void out(){
if(!hasGoods){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("消費線程名稱:"+Thread.currentThread().getName()+"消費商品爲"+this.name);
hasGoods = false;
notify();
}
}
主代碼:
public class ThreadMain {
public static void main(String[] args) {
Resources resources = new Resources();
new Producter(resources).start();
new Producter(resources).start();
}
}