1. 程式人生 > >線程的生產者消費者問題

線程的生產者消費者問題

gen int watch () nts user bool 順序執行 lag

package xiancheng;
/**
* wait() 等待 ,釋放鎖 sleep 不釋放鎖
* @author User
*
*/

public class lianxi20 {
//t 生產者生產 通知消費 f 消費者消費 通知生產
private boolean flag=true;
//模擬生產的物品
private String picString;
//生產
public synchronized void play(String picString){
//當flag為false狀態,是生產者停止工作,進入等待狀態
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//模擬生產時間
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//執行生產
this.picString=picString;

//通知消費
this.notifyAll();
//生產者停下
this.flag=false;


}
//消費
public synchronized void watch(){
//當flag為true 消費者停止等待 進入等待狀態
if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//模擬消費過程
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//進行消費操作
System.out.println(picString);
//通知生產
this.notify();
//消費者停止
this.flag=true;
}

}

/**
* 生產者
* @author User
*
*/
public class lianxi21 implements Runnable{
//定義資源
private lianxi20 m;
//定義含參構造器
public lianxi21(lianxi20 m) {
this.m = m;
}
//重寫run方法 進行生產操作
@Override
public void run() {
for(int i=0;i<20;i++){
if (0==i%2) {
m.play("傻光");
}else {
m.play("春光");
}
}
}

}

/**
* 消費者
* @author User
*
*/
public class lianxi22 implements Runnable{
//定義資源
private lianxi20 m;
//定義含參構造器
public lianxi22(lianxi20 m) {
this.m = m;
}
//重寫run方法,線程執行是進行watch操作
@Override
public void run() {
for(int i=0;i<20;i++){
m.watch();
}
}

}

public class lianxi23 {
public static void main(String[] args) {
//共同的資源
lianxi20 m=new lianxi20();
//定義生產者
lianxi21 p=new lianxi21(m);
//定義生產者
lianxi22 w=new lianxi22(m);
//線程進行
new Thread(p).start();
new Thread(w).start();
}

}

通過解決生產者消費者問題實現多線程的順序執行問題..

線程的生產者消費者問題