線程的死鎖
如果多個線程操作多個對象互相請求,那麼會引起死鎖。
package deadlock;
public class SomeBody {
private String name;
private SomeBody other;
public SomeBody(String name)
{
this.name=name;
}
public synchronized void saySomeThing()
{
System.out.println(this.name+"1111111111"+Thread.currentThread());
//某個對象進入此鎖後,休息一會,確保同時另外一個對象已經佔有它自己的鎖,
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
other.singSomeThing();//讓另外一個對象請求它已經佔有的鎖
System.out.println(this.name+"222222222222"+Thread.currentThread());
System.out.println(this.name+"33333333333"+Thread.currentThread());
System.out.println(this.name+"44444444444"+Thread.currentThread());
}
public synchronized void singSomeThing()
{
System.out.println(this.name+"AAAAAAAAAAA"+Thread.currentThread());
System.out.println(this.name+"BBBBBBBBBBBBBB"+Thread.currentThread());
// 某個對象進入此鎖後,休息一會,確保同時另外一個對象已經佔有它自己的鎖,
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
other.saySomeThing();//讓另外一個對象請求它已經佔有的鎖
System.out.println(this.name+"CCCCCCCCCCCC"+Thread.currentThread());
System.out.println(this.name+"DDDDDDDDDDDDD"+Thread.currentThread());
}
public void setOther(SomeBody other)
{
this.other=other;
}
}
線程1:
ublic class xiaoming extends Thread{
private SomeBody somebody;
public xiaoming(SomeBody somebody)
{
this.somebody=somebody;
}
public void run()
{
somebody.saySomeThing();
}
}
線程2:
package deadlock;
public class dagang extends Thread{
private SomeBody somebody;
public dagang(SomeBody somebody)
{
this.somebody=somebody;
}
public void run()
{
somebody.singSomeThing();
}
}
程序入口:
package deadlock;
public class main {
public static void main(String args[])
{
SomeBody mingming=new SomeBody("小明");
SomeBody ganggang=new SomeBody("大剛");
mingming.setOther(ganggang);
ganggang.setOther(mingming);
Thread thread1=new xiaoming(mingming);
Thread thread2=new dagang(ganggang);
thread1.start();
thread2.start();
}
}
結果:
小明1111111111Thread[Thread-0,5,main]
大剛AAAAAAAAAAAThread[Thread-1,5,main]
大剛BBBBBBBBBBBBBBThread[Thread-1,5,main]