需求:無限循環交替打印出"張三,女","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類中。