匿名類中的this 和lambda中this 的區別

匿名類:
例如1:
new Runnable() {
    @Override
    public void run() {
    }
}

替換:()-> {} 就是lambda語法;

 

*****   lambda表達式中的this指的是所在的外部類,而匿名內部類中this指的是匿名內部類當前對象

 

/** 死鎖的suspend/resume。 suspend並不會像wait一樣釋放鎖,故此容易寫出死鎖代碼 */
    //同步代碼中使用suspend、resume方法
    public void suspendResumeDeadLockTest() throws InterruptedException {
        // 啓動線程
        Thread consumerThread = new Thread(
//                new Runnable() {
//            public void run() {
//                if (baozidian == null) { // 如果沒包子,則進入等待
//                    System.out.println("1、進入等待");
//                    // 當前線程拿到鎖,然後掛起
//                    synchronized (this) {   //new Runable下使用this時,無法造成死鎖,因爲new Runnable的this對象所指的是該匿名類的對象本身。
//                        System.out.println(System.identityHashCode(this));
//                        Thread.currentThread().suspend();
//                    }
//                }
//                System.out.println("2、買到包子,回家");
//            }
//        }
                ()->{                if (baozidian == null) { // 如果沒包子,則進入等待
                    System.out.println("1、進入等待");
                    // 當前線程拿到鎖,然後掛起
                    synchronized (this) {   //lambda表達式下this時,造成死鎖,因爲lambda表達式下的this指的是lambda表達式的外部類對象,即:Demo.class對象。
                        System.out.println(System.identityHashCode(this));
                        Thread.currentThread().suspend();
                    }
                }
                    System.out.println("2、買到包子,回家");
                }
        );
        consumerThread.start();
        // 3秒之後,生產一個包子
        Thread.sleep(3000L);
        baozidian = new Object();
        // 爭取到鎖以後,再恢復consumerThread
        synchronized (this) {
            System.out.println(System.identityHashCode(this));
            consumerThread.resume();
        }
        System.out.println("3、通知消費者");
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章