需求:无限循环交替打印出"张三,女","zhangsan,famle" 定义两个线程。
注意同步的条件:1.至少有两个线程在对同一资源进行操作。2.具有相同的锁。同步函数的锁是this,静态函数的锁是类.class
</pre><pre name="code" class="java">class Resource
{
String name;
String sex;//改变age范围
}
class Input implements Runnable
{
private Resource res;
Input(Resource res)
{
this.res=res;
}
public void run()
{
boolean flag=false;
int x=0;//也就是x=0时打印中文,x=1时打印英文
while (true)
{
synchronized(res)
{
if (flag)
try{res.wait();}catch (Exception e) { System.out.println(e.toString());}
{
if (x==0)
{
res.name="张三";
res.sex="女";
}
else
{
res.name="zhangsan";
res.sex="famle";
}
flag=true;
res.notify();
}
}
x=(x+1)%2;
}
}
}
class Output implements Runnable
{
private Resource res;
Output(Resource res)
{
this.res=res;
}
public void run()
{
boolean flag=false;
while (true)
{
synchronized(res)
{
if (flag)
try{res.wait();}catch (Exception e) { System.out.println(e.toString());}
{
System.out.println(res.name+"---"+res.sex);
flag=true;
res.notify();
}
}
}
}
}
class DeadLock
{
public static void main(String[] args)
{
Resource res=new Resource();
Input in=new Input(res);
Output out =new Output(res);
Thread t1=new Thread(in);
Thread t2=new Thread(out);
t1.start();
t2.start();
}
}
如果不加同步锁的话会出现打印出"张三,famle" ,造成该现象原因:还未对张三的性别进行赋值的时候就被输出线程抢走执行权输出了。
如果不加标志位flag会出现打印出
zhangsan---famle
zhangsan---famle
zhangsan---famle
这样的话前面的交替代码就没意义了,解决这个问题的方法就是定义标志位,用等待和唤醒机制进行处理,详细的在代码中可以看见。
wait()、notify()这些方法在操作同步线程时,都需要标识他们操作线程所具有的锁。
等待和唤醒必须是同一个锁,不可以对不同锁的线程进行唤醒。
锁可以使任意对象,所以这些方法定义在Object类中。