- class Mylock{
- Object locka = new Object();
- Object lockb = new Object();
- //在毕老师的视频中这里是静态修饰锁对象,static Object locka = new Object();
- // Static Object lockb = new Object();
- //这个程序锁不住,大家说一下自己的看法,我我也不知道这样怎么就不能锁住。
- }
- class DeadLock implements Runnable{
- private boolean flag;
- Mylock m = new Mylock();
- DeadLock(boolean flag){
- this.flag = flag;
- }
- public void run(){
- if(flag){
- while(true){
- synchronized(m.locka){
- System.out.println("if locka");
- try{Thread.sleep(20);}catch(Exception e){}
- synchronized(m.lockb){
- System.out.println("if lockb");
- }
- }
- }
- }else{
- while(true){
- synchronized(m.lockb){
- System.out.println("else lockb");
- synchronized(Mm.locka){
- System.out.println("else locka");
- }
- }
- }
- }
- }
- }
- class LockDemo{
- public static void main(String[] args){
- Thread t1 = new Thread(new DeadLock(true));
- Thread t2 = new Thread(new DeadLock(false));
- t1.start();
- t2.start();
- }
- }
复制代码
|
|