1.产生死锁:
public class LockThread {
private static final Object lock1 = new Object();
private static final Object lock2 = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock1) {
System.out.println(Thread.currentThread().getName()+"锁住lock1");
synchronized (lock2) {
System.out.println(Thread.currentThread().getName()+"锁住lock2");
}
}
}
},"线程t1");
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock2) {
System.out.println(Thread.currentThread().getName()+"锁住lock2");
synchronized (lock1) {
System.out.println(Thread.currentThread().getName()+"锁住lock1");
}
}
}
},"线程t2");
t1.start();
t2.start();
}
}
2. 解开死锁:
public class LockThread {
private static final Object lock1 = new Object();
private static final Object lock2 = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock1) {
System.out.println(Thread.currentThread().getName()+"锁住lock1");
synchronized (lock2) {
System.out.println(Thread.currentThread().getName()+"锁住lock2");
}
}
}
},"线程t1");
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock1) {
System.out.println(Thread.currentThread().getName()+"锁住lock2");
synchronized (lock2) {
System.out.println(Thread.currentThread().getName()+"锁住lock1");
}
}
}
},"线程t2");
t1.start();
t2.start();
}
}