- class TestLock implements Runnable
- {
- private boolean flag;
- TestLock(boolean flag)
- {
- this.flag=flag;
- }
- public void run()
- {
- if (flag)
- { while(true)
- {
- synchronized (Lock.n1)
- {System.out.println("IF Locka");
- synchronized(Lock.n2)
- {
- System.out.println("IF Lockb");
- }
- }
- }}
- else
- while(true)
- {{
- synchronized (Lock.n2){
- System.out.println("else Locka");
- synchronized (Lock.n1){
- System.out.println("else Lockb");
- }
- }
- }
- }}
- }
- class Lock{
- Lock(){}
- static Lock n1=new Lock();
- static Lock n2=new Lock();
- }
- class DeadLock{
- public static void main(String args[])
- {
- System.out.println("Hello");
- Thread t1=new Thread(new TestLock(true));
- Thread t2=new Thread(new TestLock(false));
- t1.start();
- t2.start();
- }
- }
复制代码 这个是毕老师视频中的一个例子,我知道synchronized()是以两个不同的lock对象传入,但是毕老师在卖票例子中举得this跟obj是不同锁,为什么在这个里面传入obj跟this就不会产生死锁现象呢? |