相互等待对方占用的资源(锁)
package thread;
/*
* 死锁的使用
*/
public class Thread_9 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Mythod1 t1 = new Mythod1(0);
Mythod1 t2 = new Mythod1(1);
t1.start();
t2.start();
}
}
class Mythod1 extends Thread{
private static String lock1 = new String();//使用static使main中对象都是得到静态对象的lock
private static String lock2 = new String();
private int flag;
public Mythod1(int flag){
this.flag = flag;
}
@Override
public void run() {
if(flag == 0){
synchronized (lock1) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("t1使用lock1");
synchronized (lock2) {
}
}
}else if(flag == 1){
synchronized (lock2) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("t2使用lock2");
synchronized (lock1) {
}
}
}
}
}
请关注“知了堂学习社区”,地址:http://www.zhiliaotang.com/portal.php