匿名类:
例如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、通知消费者");
}