- class Test implements Runnable{
- private boolean flag;
- Test(boolean flag){
- this.flag=flag;
- }
- public void run(){//实现Runnable接口,复写run方法
- if(flag){
- synchronized(Mylock.locka) {
- System.out.println("if locka");
- synchronized(Mylock.lockb){
- System.out.println("if lockb");
- }
- }
- }
- else{
- synchronized(Mylock.lockb) {
- System.out.println("else lockb");
- synchronized(Mylock.locka){
- System.out.println("else locka");
- }
- }
- }
- }
- }
- //定义锁
- class Mylock{
- static Object locka=new Object();
- static Object lockb=new Object();
- }
- public class DeadLockDemo {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Thread t1=new Thread(new Test(true));
- Thread t2=new Thread(new Test(false));
- t1.start();
- t2.start();
- }
- }
复制代码
|