- package cn.itcast.demo02_死锁的问题;
- public class MyThread2 extends Thread{
- private MyClass1 c1;
- private MyClass2 c2;
- public MyThread2(MyClass1 c1 , MyClass2 c2){
- this.c1 = c1;
- this.c2 = c2;
- }
- public void run() {
- synchronized (c2) {
- System.out.println("t2锁住c2......");
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("t2即将访问show1()......");
- c1.show1();
-
- }
- System.out.println("t2释放了c2的锁......");
- }
- }package cn.itcast.demo02_死锁的问题;
- public class MyThread1 extends Thread {
- private MyClass1 c1;
- private MyClass2 c2;
- public MyThread1(MyClass1 c1 , MyClass2 c2){
- this.c1 = c1;
- this.c2 = c2;
- }
-
- @Override
- public void run() {
- synchronized (c1) {
- System.out.println("t1锁住c1......");
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("t1即将访问show2()......");
- c2.show2();
-
- }
- System.out.println("t1释放了c1的锁......");
- }
- }
- package cn.itcast.demo02_死锁的问题;
- public class MyClass2 {
- public synchronized void show2(){
- System.out.println("show2()");
- }
- }
- package cn.itcast.demo02_死锁的问题;
- public class MyClass1 {
- public synchronized void show1(){
- System.out.println("show1()");
- }
- }
- package cn.itcast.demo02_死锁的问题;
- public class Demo {
- public static void main(String[] args) {
- MyClass1 c1 = new MyClass1();
- MyClass2 c2 = new MyClass2();
-
- MyThread1 t1 = new MyThread1(c1,c2);
- MyThread2 t2 = new MyThread2(c1,c2);
-
- t1.start();
- t2.start();
-
- }
- }
复制代码 |
|