信號燈解決同步問題
我盡量注釋了代碼,可以很容易理解了。
package Thread;
/**
* 信號燈
* 借助標志位
*/
public class FlagThread {
public static void main(String[] args) {
Bread bread=new Bread();
new Producer(bread).start();
new Consume(bread).start();
}
}
class Consume extends Thread{
Bread bread;
public Consume(Bread bread) {
super();
this.bread = bread;
}
@Override
public void run() {
for(int i=1;i<100;++i) {
bread.consume();
}
}
}
class Producer extends Thread{
Bread bread;
public Producer(Bread bread) {
super();
this.bread = bread;
}
@Override
public void run() {
for(int i=1;i<100;++i) {
bread.produce();
}
}
}
//資源
//同步方法要放在資源里,沒有交點不會相互喚醒
class Bread{
//為T表示面包在生產,為F表示可以消費了
boolean flag;//標志位,定義在需要被操控的類里面
public Bread() {//構造方法初始化flag=true
flag=true;
}
public synchronized void produce(){//同步方法用來操控生產
if(!this.flag) {//如果標志位為false,生產者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}//如果標志位為true,那就生產,生產之后吧flag設置為false
System.out.println(Thread.currentThread ().getName ()+"正在生產······");//這是這句話的臨界資源
this.flag=!this.flag;
this.notifyAll();
}
public synchronized void consume(){
if(this.flag) {//如果flag為真,說明沒有面包,需要等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}//否則等待
System.out.println(Thread.currentThread ().getName ()+"正在消費·····");
this.flag=!this.flag;
this.notifyAll();
}
}
