/*
多线程之等待唤醒练习
线程运行到wait时 会一直停在那里等待 一直到被唤醒
*/
//实现双线程依次打印show2->show1->show2->show1....
class Demo
{
//标识 实现打印show2-show1-show2...
boolean b;
Demo(boolean b)
{
this.b = b;
}
/*synchronized*/ void show1(int i)
{
// System.out.println(i);
//锁对象定义的是obj1
//个人疑问: 【如果用到wait 定义不同锁对象的效果是否会不按规则打印】
synchronized(myLock.obj1){ //IllegalMonitorStateException 监视器异常?
if(b)
try{wait();}catch(Exception e){} //此代码会将线程T-0处于等待状态 并不会再往下执行
System.out.println("-----------show1---------i="+i+" "+Thread.currentThread().getName());
b = true;
notify();
}
}
/*synchronized*/ void show2(int i)
{
//锁对象定义的是obj2
synchronized(myLock.obj2){
if(!b)
try{wait();}catch(Exception e){}
System.out.println("-----------show2---------i="+i+" "+Thread.currentThread().getName());
b = false;
notify();
}
}
}
class myLock
{
//定义两个锁
public static Object obj1 = new Object();
public static Object obj2 = new Object();
}
class Test1 implements Runnable
{
Demo d;
Test1(Demo d)
{
this.d = d;
}
public void run()
{
for(int i = 1;i<=3;i++)
d.show1(i);
}
}
class Test2 implements Runnable
{
Demo d;
Test2(Demo d)
{
this.d = d;
}
public void run()
{
for(int i = 1;i<=3;i++)
d.show2(i);
}
}
class WaitDemo
{
public static void main(String[] args)
{
Demo d = new Demo(true);
Test1 te1 = new Test1(d);
Test2 te2 = new Test2(d);
Thread t1 = new Thread(te1);
Thread t2 = new Thread(te2);
t1.start();
t2.start();
}
}
为什么我使用不同对象锁时就出了异常 运行异常!!
求大神 谢谢~~
小弟初学者。