//什么意思呢interfaceFoo{
int div ();}//我们就可以这么做Foo f =()->{
写实现;return 值;};
f.div();即可
// 对于有返回值有参数的interfaceFoo{
int div (int a,int b);}Foo f =(a, b)->{
写实现; return 值};
f.div(1,2);就可以
线程间的通信
一个进程内, 线程间的协调和调度, 操作共享资源。
不同进程间的通信得利用操作系统中讲的进程通信。
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;/**
* @author xiaofei
* @create 2021-07-28 9:53
*//*
* 题目: 现在两个线程, 可以操作初始值位零的一个变量,
* 实现一个进程对变量加一, 一个线程对改变量减一
* 实现交替, 来10轮, 变量初始值为零
*
*
* 1、高内聚低耦合, 线程操作资源类
* 2、判断/干活/通知
* 3、多线程交互中, 必须要防止多线程的续集唤醒, 也即 (判断使用while不
* 能用if)
* 4、标志位
* 唤醒的时候还必须在判断
* */classAirConditioner{
privateint num =0;private Lock lock =newReentrantLock();public synchronized voidadd() throws InterruptedException {
//这种情况会出错的原因是线程被唤醒的时侯就不需要在拍段一次条件了故在面对超过两个线程的时候就出现错误// if (num != 0) this.wait();// num ++;// System.out.println(Thread.currentThread().getName() + " " + num);//// this.notifyAll();//第一种解决办法while(num !=0)this.wait();
num ++;
System.out.println(Thread.currentThread().getName()+" "+ num);this.notifyAll();//第二种解决办法 说到底都是 让其唤醒的时候在经历一次判断 另外这样写可能打出来的结果可能不是40行// 因为被唤醒之后就不是去去执行本次的操作而是直接本次操作结束 执行 i++ 了// if (num == 0) {
// num ++;// System.out.println(Thread.currentThread().getName() + " " + num);// this.notifyAll();// }else// this.wait();}public synchronized voidsub() throws InterruptedException {
while(num ==0)this.wait();
num --;
System.out.println(Thread.currentThread().getName()+" "+ num);this.notifyAll();// if (num == 1) {
// num --;// System.out.println(Thread.currentThread().getName() + " " + num);// this.notifyAll();// }else// this.wait();}}publicclassThreadWaitNotifyDemo{
publicstaticvoidmain(String[] args) throws Exception{
AirConditioner airConditioner =newAirConditioner();newThread(()->{
try{
// for (int i = 0; i < 10; i ++) airConditioner.sub();while(true) airConditioner.sub();}catch(InterruptedException e){
e.printStackTrace();}},"B").start();newThread(()->{
try{
// for (int i = 0; i < 10; i ++) airConditioner.add();while(true) airConditioner.sub();}catch(InterruptedException e){
e.printStackTrace();}},"A").start();newThread(()->{
try{
// for (int i = 0; i < 10; i ++) airConditioner.add();while(true) airConditioner.add();}catch(InterruptedException e){
e.printStackTrace();}},"c").start();newThread(()->{
try{
// for (int i = 0; i < 10; i ++) airConditioner.sub();while(true) airConditioner.