a- package demo;
- public class DeadLockDemo {
- public static void main(String[] args) {
- final M m = new M();
- new Thread(){
- public void run() {
- while (true)
- m.run();
- };
- }.start();
- new Thread() {
- public void run() {
- while (true)
- m.go();
- };
- }.start();
- }
- }
- class M {
- Object lock1 = new Object();
- Object lock2 = new Object();
- public void run(){
- synchronized(lock1){ //嵌套锁
- System.out.println("lock1 run()"+Thread.currentThread().getName());
- synchronized(lock2){
- System.out.println("lock2 run()"+Thread.currentThread().getName());
- }
- }
- }
- public void go(){
- synchronized(lock2){
- System.out.println("go run()"+Thread.currentThread().getName());
- synchronized(lock1){
- System.out.println("go run()"+Thread.currentThread().getName());
- }
- }
- }
- }
复制代码- lock1 run()Thread-0
- lock2 run()Thread-0
- lock1 run()Thread-0
- lock2 run()Thread-0
- lock1 run()Thread-0
- go run()Thread-1
复制代码
|
|