java信号灯_java 多线程-信号灯法
借助標志位
public class light {
public static void main(String[]args)
{
Tv tv=new Tv();
new Player(tv).start();
new Watcher(tv).start();
}
}
//生產者 演員
class Player extends Thread{
Tv tv;
public Player(Tv tv)
{
this.tv=tv;
}
public void run()
{
for(int i=0;i<20;i++)
{
if(i%2==0)
{
this.tv.play("偶不變");
}else
{
this.tv.play("奇變");
}
}
}
}
//消費者 觀眾
class Watcher extends Thread{
Tv tv;
public Watcher(Tv tv)
{
this.tv=tv;
}
public void run()
{
for(int i=0;i<20;i++)
{
this.tv.watch("無聊");
}
}
}
//同一個資源 電視
class Tv {
String voice;
//信號燈
//為真則演員表演,觀眾等待
//為假則觀眾觀看,演員等待
boolean flag=true;
//表演
public synchronized void play(String voice)
{
if(!flag)
{
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("表演了:"+voice);
this.voice=voice;
//表演后
this.notifyAll();
this.flag=!this.flag;
}
public void watch(String string) {
// TODO Auto-generated method stub
}
//觀看
public synchronized void watch()
{
if(flag)
{
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("聽到了:"+voice);
//觀看后:
this.notifyAll();
this.flag=!this.flag;
}
}
總結
以上是生活随笔為你收集整理的java信号灯_java 多线程-信号灯法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ssh excel 导入 mysql_s
- 下一篇: java servlet 输出_Java