信号灯法验证线程
- 这里设置了一个boolean的值,默认值是false
- 这里面有二个线程,二个线程同时进入到TV(想象为容器)这个容器中 ,去拿数据!
- 注意这里有一个boolean类型的灯!! 线程进去寻找方法! 当boolean !=true的时候,生产表演了+voice!
- 当boolean==false的时候!就进去了!!然后睡眠 super.wait()等待; super.notify()唤醒对方!
- 如果满足条件!例如第一个play方法满足! boolean 默认值 flag=false的; 如果满足if判断!就要进去!进去遇到 super.wait() 就开始等待!让对方表演!当末尾的flag=true的时候! 又走到 watch方法的if判断! watch方法里,if判断(flagfalse) 而flagtrue; 所以执行下面的数据!产生观看了+THIS.voice 以此类推
- .
上源码:
public class TestThread {
public static void main(String[] args) {
TV tv=new TV();
new Play(tv).start();
new Watch(tv).start();
//这里不会报异常,因为没有数组
}
}
/**
* 表演类
* @author 戴尔
*
*/
class Play extends Thread{
TV tv;
public Play(TV tv) {
this.tv=tv;
}
@Override
public void run() {
for (int i = 1; i <= 20; i++) {
if (i % 2==0) {//play 表演的有点区别
tv.play("末日崩塌");
}else {
tv.play("看动漫");
}
}
}
}
/**
* 观看类
* @author 戴尔
*
*/
class Watch extends Thread{
TV tv;
public Watch(TV tv) {
this.tv=tv;
}
@Override
public void run() {
for (int i = 1; i <=20; i++) {
tv.watch();
}
}
}
class TV{
boolean flag=false;
String voice;
public synchronized void play(String voice) {
if (flag==true) {
try {
super.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.voice=voice;
System.out.println("表演了,"+voice);
super.notify();
flag=true;
}
/**
* 观看方法
*/
public synchronized void watch(){
if (flag==false) {
try {
super.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("观看了!"+this.voice);
super.notify();
flag=false;
}
}
部分运行结果!!
表演了,看动漫
观看了!看动漫
表演了,末日崩塌
观看了!末日崩塌