目标: 使用Java完成多线程的死锁操作,
这里使用实现Runnable接口操作,因为这样的话只需要创建一个对象既可完成被多个线程的操作。
class Runn implements Runnable{
private Object object1 = new Object();
private Object object2 = new Object();
private boolean flag = true;
@Override
public void run() {
if(flag){
flag = false;
synchronized (object1){
System.out.println(Thread.currentThread().getName() + " object1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object2){
System.out.println(Thread.currentThread().getName() + " object2");
}
}
}else{
flag = true;
synchronized (object2){
System.out.println(Thread.currentThread().getName() + " object2");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object1){
System.out.println(Thread.currentThread().getName() + " object1");
}
}
}
}
}
public class Wwe{
public static void main(String[] args) {
Runn runn = new Runn();
new Thread(runn,"A").start();
new Thread(runn,"B").start();
}
}