java多線程之生產者消費者問題

/*測試類
 * 這裏創建了6個線程,模擬3個生產者,3個消費者
 */
public class TestThread {
public static void main(String[] args) {
Lanzi lz = new Lanzi();
Producer p = new Producer(lz);
Comsumer cs = new Comsumer(lz);
new Thread(p,"生產者1").start();
new Thread(p,"生產者2").start();
new Thread(p,"生產者3").start();
new Thread(cs,"消費者1").start();
new Thread(cs,"消費者2").start();
new Thread(cs,"消費者3").start();
}


}


/*產品類*/
class ManTou{
int id;
public ManTou(int id){
this.id = id;
}
public String toString(){
return "ManTou" + id;
}
}


/*倉庫類
 * 裏面有兩個同步方法pop,push,分別用來代表生產和消費的。
 * */
class Lanzi{
int index = 0;
ManTou[] wo = new ManTou[10];
public synchronized void push(ManTou ManTou){
while(index == wo.length){//這裏用的是while,而不是用if,保證每次拿到鎖的線程都會檢查一次,不然就會出錯
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.notifyAll();
wo[index] = ManTou;
index ++;
System.out.println(Thread.currentThread().getName()+"生產了"+ManTou);
}
public synchronized ManTou pop(){
while(index == 0){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.notifyAll();
index --;
ManTou ManTou = wo[index];
wo[index] = null;
System.out.println(Thread.currentThread().getName()+"消費了"+ ManTou);
return ManTou;
}

}


/*生產者*/
class Producer implements Runnable{
Lanzi lz = null;
ManTou ManTou = null;
int i = 1;

public Producer(Lanzi lz){
this.lz = lz;
}
boolean flag = true;

public void run() {
while(flag){//這裏用死循環模擬源源不斷的生產過程,也可以用for循環模擬生產的次數
ManTou = new ManTou(i);
lz.push(ManTou);
i++;
//System.out.println(i);
//if(i == 4) flag = false;  //這裏可以控制循環的次數
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}



/*消費者*/
class Comsumer implements Runnable{
Lanzi lz = null;
boolean flag = true;
public Comsumer(Lanzi lz){
this.lz = lz;
}

public void run() {
while(flag){
lz.pop();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}

以上內容爲個人學習多線程時所編寫的代碼,主要是作爲一種學習的筆記,如有什麼問題,請見諒,謝謝。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章