java基础-day22-多线程、线程通信和线程池

多线程,线程通信和线程池

1. 多线程

1.1 线程状态
image.png
1.2 Object类中的方法
wait();
    1. 在哪一个线程中执行,哪一个线程就进入休眠状态【调用方法者为锁对象】
    2. wait方法可以让当前线程进入休眠状态,同时【打开锁对象】
    
notify();
    1. 唤醒一个线程,和当前调用方法【锁对象】相关线程
    2. notify方法在唤醒线程的过程中,可以打开【锁对象】
    
notifyAll();
    1. 唤醒和当前调用方法【锁对象】相关所有线程
    2. notifyAll方法在唤醒所有线程的过程中,同时会开启锁对象。

2. 线程通信 生产者消费者案例

2.1 分析问题
image.png
2.2 代码实现
package com.qfedu.a_thread;

class Producer implements Runnable {

    Goods goods;

    public Producer() {
    }

    public Producer(Goods goods) {
        this.goods = goods;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (goods) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                
                // 商品需要生产
                if (goods.isProduct()) {
                    if (Math.random() > 0.5) {
                        goods.setName("吉利星越");
                        goods.setPrice(10);
                    } else {
                        goods.setName("领克05");
                        goods.setPrice(15);
                    }
                    System.out.println("生产者生产:" + goods.getName() + " 价格" + goods.getPrice());
                    // 修改生产标记
                    goods.setProduct(false);

                    // 唤醒消费者
                    goods.notify();
                    System.out.println("唤醒消费者");
                } else {
                    // 生产者进入休眠状态
                    System.out.println("生产者休眠");
                    try {
                        goods.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}

class Customer implements Runnable {

    Goods goods;

    public Customer() {
    }

    public Customer(Goods goods) {
        this.goods = goods;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (goods) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                // 消费者买买买状态
                if (!goods.isProduct()) {
                    System.out.println("消费者购买:" + goods.getName() + " 价格" + goods.getPrice());

                    // 修改生产标记
                    goods.setProduct(true);

                    // 唤醒生产者
                    System.out.println("唤醒生产者");
                    goods.notify();
                } else {
                    // 消费者进入休眠状态
                    System.out.println("消费者休眠");
                    try {
                        goods.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}

class Goods {
    private String name;
    private int price;
    private boolean product;

    public Goods() {
    }

    public Goods(String name, int price, boolean product) {
        this.name = name;
        this.price = price;
        this.product = product;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public boolean isProduct() {
        return product;
    }

    public void setProduct(boolean product) {
        this.product = product;
    }
}

public class Demo1 {
    public static void main(String[] args) {
        Goods goods = new Goods("领克05", 15, true);

        Producer producer = new Producer(goods);
        Customer customer = new Customer(goods);

        System.out.println(producer.goods);
        System.out.println(customer.goods);

        new Thread(producer).start();
        new Thread(customer).start();

    }
}

3. 线程池

3.1 线程池需求
目前情况下操作线程对象
    1. 继承Thread类,重写run方法,创建对象,start方法启动线程
    2. 遵从Runnable接口,实现run方法,创建Thread类对象,start启动线程
    以上两种方式,都是在确定run方法之后(What will be run 跑啥)!!!后期线程在运行的过程中,任务是明确的无法替换的!!!

生活中的例子:
    吃饭
        服务员
        在提供服务的过程中,需要监视每一个桌子
        如果发现有顾客需要提供服务,立马执行!!!
    
    一个餐厅10张桌子,有5个服务员
    5个服务员我们可以看做是5个线程,具体做什么任务,由用户指定。 
3.2 线程池工作图例
image.png
3.3 低端版线程池方法和操作
class Executors
public static ExecutorService newFixedThreadPool(int nThreads);
    得到一个线程池对象,传入参数为当前线程池中默认存在的线程对象有多少个。

ExecutorService
Future<?> submit(Runnable task);
    提交任务给当前线程池,需要的参数是Runnable接口对象。
package com.qfedu.a_thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/*
 * 线程池使用
 */
public class Demo4 {
    public static void main(String[] args) {
        /*
         * 得到了一个线程池,目前线程池中有5个线程对象
         */
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        
        System.out.println(threadPool);
        /*
         * java.util.concurrent.ThreadPoolExecutor@7852e922
         * [Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]
         * 线程池状态 Running 正在运行 
         * pool size = 0  当前线程池线程容量
         * active threads 目前正在运行线程对象
         * queued tasks 排队任务
         * completed tasks 完成任务
         */
        
        threadPool.submit(new Runnable() {          
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName());
                System.out.println("线程池对象执行代码中");   
            }
        });
        
        threadPool.submit(() -> {
            System.out.println(Thread.currentThread().getName());
            System.out.println("线程池对象执行代码中");   
        });
        
        System.out.println(threadPool);
    }
}

4. Lambda表达式【 JDK1.8新特征】

4.1 说重点
接口和实现类
    interface A {
        void testA();
    }
    
    class TypeA implements A {
        @Override
        public void testA() {
            Sout("测试");
        }
    }
    
    main() {
        new TypeA().testA();
    }
    1. 实现了一个类
    2. 完成对应方法
    3. 创建实现类对象
    4. 调用方法 【核心】

Lambda表达式!!!
    C语言 方法指针
    PHP JS 匿名方法
    Objective-C Block代码块
基本格式:
    (参数名字) -> {
        和正常完成方法一致!!!
    }
4.2 无参数无返回值Lambda
package com.qfedu.b_lambda;

/*
 * 函数式接口 有且只允许在接口中有一个未实现方法
 */
@FunctionalInterface
interface A {
    void test();
}

public class Demo1 {
    public static void main(String[] args) {
        // 匿名内部类作为方法的参数
        testInterface(new A() {
            
            @Override
            public void test() {
                System.out.println("匿名内部类 low~~~");
            }
        });
        
        // 无参数无返回值lambda表达式使用,因为有且只有一句话,大括号可以省略
        testInterface(() -> System.out.println("无参数无返回值lambda"));
    }
    
    public static void testInterface(A a) {
        a.test();
    }
}
4.3 有参数无返回值Lambda
package com.qfedu.b_lambda;

import java.util.ArrayList;
import java.util.Comparator;

@FunctionalInterface
interface B {
    /*
     * 有参数无返回值方法,并且参数数据类型有传入参数类型 本身决定
     */
    void test(String str);
}

public class Demo2 {
    public static void main(String[] args) {
        testInterface("测试", new B() {

            @Override
            public void test(String str) {
                System.out.println(str);
            }
        });

        /*
         * lambda表达式参数需要养成习惯 1. 缺省数据类型 2. 脑补数据类型,自定义参数名字
         */
        testInterface("abcdefg", (s) -> {
            String str = s.toUpperCase();
            System.out.println(str);
        });

        System.out.println();
        ArrayList<SinglePerson> list = new ArrayList<SinglePerson>();

        list.add(new SinglePerson("小赵", 16, '男'));
        list.add(new SinglePerson("小钱", 14, '男'));
        list.add(new SinglePerson("小孙", 12, '男'));
        list.add(new SinglePerson("小李", 1, '男'));
        list.add(new SinglePerson("小周", 0, '男'));
        list.add(new SinglePerson("小五", 6, '男'));

        list.sort(new Comparator<SinglePerson>() {
            @Override
            public int compare(SinglePerson o1, SinglePerson o2) {
                return o1.getAge() - o2.getAge();
            }
        });

        // Lambda表达式
        list.sort((o1, o2) -> o1.getAge() - o2.getAge());

        list.sort(Comparator.comparingInt(SinglePerson::getAge));

        for (SinglePerson singlePerson : list) {
            System.out.println(singlePerson);
        }
    }

    public static void testInterface(String t, B b) {
        b.test(t);
    }
}
4.4 无参数有返回值Lambda
package com.qfedu.b_lambda;

@FunctionalInterface
interface C<T> {
    T get();
}

public class Demo3 {
    public static void main(String[] args) {
        testInferface(new C<Integer>() {

            @Override
            public Integer get() {
                return 1;
            }
        });
        
        // 如果return是一句话,可以省略大括号和return关键字
        testInferface(() -> {
            return 5;
        });
        
        testInferface(() -> 5);
        
        /*
         * main方法中的局部变量
         */
        int[] arr = {1, 3, 5, 7, 19, 2, 4, 6, 8, 10};
        
        testInferface(() -> {
            /*
             * lambda表达式可以使用当前所处大括号以内的局部变量
             */
            int maxIndex = 0;
            // 找出数组中最大值
            for (int i = 1; i < arr.length; i++) {
                if (arr[maxIndex] < arr[i]) {
                    maxIndex = i;
                }
            }
            
            return maxIndex;
        }); 
    }
    
    private static void testInferface(C c) {
        System.out.println(c.get());
    }
}
4.5 有参数有返回值Lambda
package com.qfedu.b_lambda;

import java.util.ArrayList;

interface D<T> {
    boolean test(T t);
}

public class Demo4 {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        
        list.add("锅包肉");
        list.add("酱肘子");
        list.add("回锅肉");
        list.add("红烧肉");
        list.add("拍黄瓜");
        list.add("韭菜炒千张");
        list.add("煎焖闷子");
        
        /*
         * 1. Lambda表达式
         * 2. Stream流式操作
         * 3. 方法引用
         * 4. 函数式接口
         */
        list.stream()
            .filter((s) -> s.contains("肉"))
            .filter(s -> s.startsWith("锅"))
            .forEach(System.out::println);
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,490评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,581评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,830评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,957评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,974评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,754评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,464评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,847评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,995评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,137评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,819评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,482评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,023评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,149评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,409评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,086评论 2 355

推荐阅读更多精彩内容