知道理论后,下面的代码就很好写了- class ThreadA extends Thread {
- private Object x;
- private Object y;
- public ThreadA(Object x, Object y) {
- this.x = x;
- this.y = y;
- }
- @Override
- public void run() {
- while (true) {
- synchronized (x) {
- System.out.println("ThreadB 以获取x。。。。");
- try {
- sleep(3000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("ThreadA 正请求y:");
- synchronized (y) {
- System.out.println("ThreadA 以获取y。。。。");
- }
- System.out.println("ThreadA 释放y,,,,");
- }
- System.out.println("ThreadA 释放x,,,,");
- }
- }
- }
- class ThreadB extends Thread {
- private Object x;
- private Object y;
- public ThreadB(Object x, Object y) {
- this.x = x;
- this.y = y;
- }
- @Override
- public void run() {
- while (true) {
- synchronized (y) {
- System.out.println("ThreadB 以获取y。。。。");
- try {
- sleep(3000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("ThreadB 正请求x:");
- synchronized (x) {
- System.out.println("ThreadB 以获取x。。。。");
- }
- System.out.println("ThreadB 释放x,,,,");
- }
- System.out.println("ThreadB 释放y,,,,");
- }
- }
- }
- public class DeadLock {
- public static void main(String[] args) {
- // 建立两个对象锁
- Object x = new Object();
- Object y = new Object();
-
- // ThreadA先获取x,然后获取y
- new ThreadA(x, y).start();
-
- // ThreadA先获取y,然后获取x
- new ThreadB(x, y).start();
-
- // synchronized关键字获取对象时,如果没有获取会一直等待查询,知道获取
- }
- }
复制代码 |