栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

多线程学习笔记

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

多线程学习笔记

多线程 1.Process与Thread
  • 说起进程,就不得不说下程序。程序是指令和数据的有序集合,其本身没有任何运行的含义,是一个静态的概念。

  • 而进程则是执行程序的依次执行过程,它是一个动态的概念。是系统资源分配的单位。

  • 通常在一个进程中可以包含若干个线程,当然一个进程中至少有一个线程,不然没有存在的意义。线程是CPU调度和执行的单位。

注意:
很多多线程是模拟出来的,真正的多线程是指有多个cpu,即多核,如服务器。如果是模拟出来的多线程,即在一个cpu的情况下,在同一个时间点,cpu只能执行一个代码,因为切换的很快,所以就有同时执行的错局。

2.核心概念
  • 线程就是独立的执行路径
  • 在程序运行时,即使没有自己创建线程,后台也会有多个线程,比如主线程,GC线程
  • main()称之为主线程,为系统的入口,用于执行整个程序
  • 在一个进程中,如果开辟了多个线程,线程的运行是由调度器(cpu)安排调度的,调度器是与操作系统紧密相关的,先后顺序是不能人为干预的
  • 对同一份资源操作时mm会存在资源抢夺的问题,需要加入并发控制
    线程会带来额外的开销,如CPU调度时间,并发控制开销
  • 每个线程在自己的工作内存交互,内存控制不当会造成数据不一致

3.线程实现
  • 继承Thread类
    • 子类继承Thread类具有多线程的能力

    • 启动线程 子类对象start

    • 不建议使用,避免OOP点继承的局限性

      public class TestThread1 extends Thread{
          @Override
          public void run() {
              //run方法线程体
              for (int i = 0; i < 20; i++) {
                  System.out.println("我在看代码~~~~"+i);
              }
          }
      
          public static void main(String[] args) {
              //main 方法 主线程
      
              //创建一个线程对象
              TestThread1 testThread1 = new TestThread1();
              testThread1.start();
      
              for (int i = 0; i < 200; i++) {
                  System.out.println("我在学习多线程~~~~~"+i);
              }
          }
      }
      
  • 实现Runnable接口
    • 实现Runnable具有多线程的能力

    • 启用线程,传入目标对象 start

    • 推荐使用,避免单继承的局限性,灵活方便,方便同一个对象被多线程使用

      public class TestThread3 implements Runnable{
      
          @Override
          public void run() {
              for (int i = 0; i < 20; i++) {
                  System.out.println("我在看代码~~~~"+i);
              }
          }
      
          public static void main(String[] args) {
      
              TestThread3 testThread3 = new TestThread3();
              Thread thread = new Thread(testThread3);
      
              thread.start();
              for (int i = 0; i < 100; i++) {
                  System.out.println("我在学习多线程~~~"+i);
              }
          }
      }
      
4.案例实现 1.案例实现-火车票
/多线程操作同一个对象的发生
public class TestThread4 implements Runnable{

    //票数
    private int tickNums = 10;
    @Override
    public void run() {
        while (true){
            if (tickNums <= 0){
                break;
            }
            //模拟延迟
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"拿到了第"+tickNums--+"张票");
        }
    }

    public static void main(String[] args) {
        TestThread4 testThread4 = new TestThread4();

        new Thread(testThread4,"小明").start();
        new Thread(testThread4,"老师").start();
        new Thread(testThread4,"黄牛").start();
    }
}
2.案例实现-龟兔赛跑

public class Race implements Runnable{

    private static String winner;
    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {

            //模拟兔子休息
            if ("兔子".equals(Thread.currentThread().getName()) && i%10==0) {
                try {
                    Thread.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println("兔子休眠ing~·");
                }
            }
            //判断比赛是否结束
            boolean b = gameOver(i);
            //如果结束 停止
            if (b){
                break;
            }
            System.out.println(Thread.currentThread().getName()+"----》跑了"+i+"步");
        }
    }
    //判断是否结束比赛
    private boolean gameOver(int steps){
        if (winner != null){
            return true;
        }{
            if (steps>=100){
                winner = Thread.currentThread().getName();
                System.out.println("winner is "+ winner);
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race,"兔子").start();
        new Thread(race,"乌龟").start();
    }
}
5.静态代理

结婚案列

public class StaticProxy {
    public static void main(String[] args) {
        WeddingCompany weddingCompany = new WeddingCompany(new you("xlh"));
        weddingCompany.marry();
    }
}

interface marry{
    void marry();
}

class you implements marry{
    String name = "xlh";

    public you(String name) {
        this.name = name;
    }

    @Override
    public void marry() {
        System.out.println("结婚了 超级开心");
    }

    @Override
    public String toString() {
        return "you{" +
                "name='" + name + ''' +
                '}';
    }
}

//代理角色 帮助你结婚
class WeddingCompany implements marry{

    private marry target;

    public WeddingCompany(marry target) {
        this.target = target;
    }

    @Override
    public void marry() {
        before();
        System.out.println("帮助别人办理结婚"+this.target);
        this.target.marry();
        after();
    }

    private void before() {
        System.out.println("布置现场");
    }

    private void after() {
        System.out.println("收钱");
    }
}
总结

真实对象和代理对象都要实现一个接口
代理对象要代理真实角色

好处

代理对象可以做很多真实对象做不了的事情
真实对象专注做自己的事

6.Lamda表达式
  • λ 希腊字母表中排序第十一位的字母,英语名称为 Lamda
  • 避免匿名内部类定义过多
  • 其实质属于函数式编程的概念
  • 去掉了一堆没有意义的代码,只留下核心逻辑

new Thread (()->System.out.println(“多线程学习。。。。”)).start();

理解Functional Interface (函数式接口) 是学习Java8 lamda表达式的关键

函数式接口的定义

任何接口,如果包含唯一一个抽象方法,那么这就是一个函数式接口

public interface Runnable{
    public abstract void run();
}

对于函数式接口,我们可以通过lambda表达式来创建接口对象

实现

案例一:

public class Demo9_Lamda {
    public static void main(String[] args) {
        ILike like = new Like();
        like.lamda();
    }
}

// 1.定义一个函数式接口
interface ILike {
    void lamda();
}

// 2.实现类
class Like implements ILike {
    @Override
    public void lamda() {
        System.out.println("I like lamda");
    }
}

优化一:静态内部类

public class Demo10_Lamda1 {
    //3. 静态内部类
    static class Like1 implements ILike {
        @Override
        public void lamda() {
            System.out.println("I like lamda1");
        }
    }
    //3.静态内部类
    public static void main(String[] args) {
        ILike like = new Like1();
        like.lamda();
    }
}

优化二:局部内部类

public class Demo11_Lamda2 {
    public static void main(String[] args) {
        //4.局部内部类
        class Like12 implements ILike {
            @Override
            public void lamda() {
                System.out.println("I like lamda2");
            }
        }
        ILike like = new Like12();
        like.lamda();
    }
}

优化三:匿名内部类

public class Demo12_Lamda3 {
    public static void main(String[] args) {
        //5.匿名内部类,没有类的名称,必须借助接口或者父类
        ILike like = new ILike () {
            @Override
            public void lamda() {
                System.out.println("I like lamda3");
            }
        };
        like.lamda();
    }
}

最终版本:

public class Demo13_Lamda4 {
    public static void main(String[] args) {
        //6.lamda简化
        ILike like = () ->{
            System.out.println("I like lamda4");
        };
        like.lamda();
    }
}

案例二:Lambda优化

public class Demo14_LamdaCase2 {
    public static void main(String[] args) {
        // 1.lamda
        ILove love = (int a) -> {
            System.out.println("I love you -->" + a);
        };
        // 2.lamda简化1.0
        love = (a) -> {
            System.out.println("I love you -->" + a);
        };
        // 3.lamda简化2.0
        love = a -> {
            System.out.println("I love you -->" + a);
        };
        // 3.lamda简化3.0
        love = a -> System.out.println("I love you -->" + a);

        

        love.love(520);
    }
}

interface ILove {
    void love(int a);
}

7.线程状态


7.1.线程方法

7.1.1停止线程

public class Demo15_StopThread implements Runnable {
    // 1. 设置一个标志位
    private boolean flag = true;

    @Override
    public void run() {
        int i = 0;
        while (flag) {
            System.out.println("run...Thread" + i++);
        }
    }

    // 2. 设置一个公开的方法停止线程,转换标志位
    public void stop() {
        this.flag = false;
    }

    public static void main(String[] args) {
        Demo15_StopThread stop = new Demo15_StopThread();
        new Thread(stop).start();
        for (int i = 0; i < 1000; i++) {
            System.out.println("main..." + i);
            if (i == 900) {
                //调用stop()切换标志位,让线程终止
                stop.stop();
                System.out.println("该线程停止了");
            }
        }
    }
}


7.1.2线程休眠

案例

public class Demo16_SleepThread implements Runnable {

    //票数
    private int ticketNums = 10;

    @Override
    public void run() {
        while (true) {
            if (ticketNums <= 0) {
                break;
            }
            //捕获异常
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "--->拿到了第" + ticketNums-- + "张票");
        }
    }

    public static void main(String[] args) {
        Demo4_TrainTicketsCase ticket = new Demo4_TrainTicketsCase();
        new Thread(ticket, "小红").start();
        new Thread(ticket, "老师").start();
        new Thread(ticket, "黄牛1").start();
    }
}

public class Demo17_SleepThread2 {

    public static void main(String[] args) {
        try {
            tenDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //模拟倒计时
    public static void tenDown() throws InterruptedException {
        int num = 10;//10秒
        while (true) {
            Thread.sleep(1000);
            System.out.println(num--);
            if (num <= 0) {
                break;
            }
        }
    }
}

public class Demo18_SleepThread3 {

    public static void main(String[] args) {
        //获取系统当前时间
        Date startTime = new Date(System.currentTimeMillis());
        while (true) {
            try {
                Thread.sleep(1000);
                //更新系统时间
                System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
                startTime = new Date(System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
7.1.3线程礼让
  • 礼让线程,让当前正在执行的线程暂停,但不阻塞
  • 将线程从运行状态转换为就绪状态
  • 让cpu重新调度,礼让不一定成功,看cpu心情

案例:

public class Demo19_YieldThread {
    public static void main(String[] args) {
        MyYeild myYeild = new MyYeild();
        new Thread(myYeild, "a").start();
        new Thread(myYeild, "b").start();
    }
}

class MyYeild implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "线程开始执行");
        Thread.yield();//礼让
        System.out.println(Thread.currentThread().getName() + "线程停止执行");
    }
}
7.1.4线程插队
  • Join合并线程吗,待此线程执行完成之后,在执行其他线程,其他线程阻塞
  • 可以想象为插队

案例

public class Demo20_JoinThread implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 500; i++) {
            System.out.println("线程vip" + i);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        //启动我们的线程
        Demo20_JoinThread joinThread = new Demo20_JoinThread();
        Thread thread = new Thread(joinThread);
        thread.start();

        //主线程
        for (int i = 0; i < 500; i++) {
            if (i == 200) {
                thread.join();//插队
            }
            System.out.println("main" + i);
        }
    }
}
7.2线程状态


案例

public class Demo21_ThreadState {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("//");
        });
        //观察状态
        Thread.State state = thread.getState();
        System.out.println(state);
        //观察启动后
        thread.start();
        state = thread.getState();
        System.out.println(state);//Run
        while (state != Thread.State.TERMINATED) {//只要现成不终止,就一直输出状态
            Thread.sleep(100);
            state = thread.getState();//更新线程状态
            System.out.println(state);
        }
        //死亡后的线程不能再启动了,启动会报异常
        //thread.start();
    }
}
7.3线程优先级
  • java提供了一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定调度哪个线程来执行

  • 线程的优先级由数字表示 范围从1-10

    线程的优先级只是以为着获得调度的概率低,并不是因为优先级低就不会被调度了,而是看cpu的调度

    优先级的设定在线程的开始之前

mian方法的优先级默认为5

public class Demo22_ThreadPriority{
    public static void main(String[] args) {
        //主线程默认优先级
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());

        MyPriority myPriority = new MyPriority();
        Thread thread1 = new Thread(myPriority);
        Thread thread2 = new Thread(myPriority);
        Thread thread3 = new Thread(myPriority);
        Thread thread4 = new Thread(myPriority);
        Thread thread5 = new Thread(myPriority);

        //先设置优先级,再启动
        thread1.start();

        thread2.setPriority(1);
        thread2.start();

        thread3.setPriority(4);
        thread3.start();

        thread4.setPriority(Thread.MAX_PRIORITY);//MAX_PRIORITY=10
        thread4.start();

        thread5.setPriority(8);
        thread5.start();
    }
}
class MyPriority implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
    }
}
7.4守护线程
  • 守护线程分为用户线程守护线程
  • 虚拟机必须确保用户线程执行完毕
  • 如后台记录操作日志,监控内存,GC垃圾回收等待

默认都是用户线程 需要调用 setDamon(ture)来设置为守护线程

用户线程执行完毕后,守护线程也执行完毕

案例

public class Demo23_DaemonThread {
    public static void main(String[] args) {
        God god = new God();
        You you = new You();

        Thread thread = new Thread(god);
        //默认false表示是用户线程,正常的线程都是用户线程...
        thread.setDaemon(true);
        //上帝守护线程启动
        thread.start();
        //你 用户线程启动
        new Thread(you).start();
    }
}

//上帝
class God implements Runnable{
    @Override
    public void run() {
        while (true){
            System.out.println("上帝保佑着你");
        }
    }
}

//你
class You implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 36500; i++) {
            System.out.println("你一生都开心的活着");
        }
        System.out.println("====goodbye!world====");
    }
}

8.线程同步 1.介绍

多个线程操作同一个资源

并发

2.线程同步

  • 由于同一个进程的多个线程同享一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据被访问的正确性,在访问的同时加入了锁机制,synchronized,当一个线程对象独占资源,其他线程必须等待。使用后释放锁即可,存在以下问题:
    • 一个线程持有锁会导致其他所有需要此锁的线程挂起
    • 在多线程竞争下,加锁,释放锁会导致较多的上下文切换,调度延时,引起性能问题。
    • 如果一个优先级高的线程等待一个优先级低的线程,释放锁,会导致优先级倒置,引发性能问题

线程的不安全案例

//不安全买票
public class Demo24_UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket, "张三").start();
        new Thread(buyTicket, "李四").start();
        new Thread(buyTicket, "王五").start();
    }
}

class BuyTicket implements Runnable {
    //票
    private int ticketNums = 10;
    boolean flag = true;

    @Override
    public void run() {
        //买票
        while (flag) {
            try {
                buy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //买票
    private void buy() {
        //判断是否有票
        if (ticketNums <= 0) {
            flag = false;
            return;
        }
        //延迟
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //买票
        System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
    }
}
public class Demo25_UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account(100, "结婚基金");
        Drawing you = new Drawing(account, 50, "展堂");
        Drawing girlfriend = new Drawing(account, 100, "sad");
        you.start();
        girlfriend.start();
    }
}

//账户
class Account {
    int money;//余额
    String cardName;//卡名

    public Account(int money, String cardName) {
        this.money = money;
        this.cardName = cardName;
    }
}

//银行:模拟取款
class Drawing extends Thread {
    Account account;//账户
    int drawingMoney;//取金额
    int nowMoney;//你手里的钱

    public Drawing(Account account, int drawingMoney, String name) {
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    //取钱
    @Override
    public void run() {
        //判断是否有钱
        if (account.money - drawingMoney < 0) {
            System.out.println(Thread.currentThread().getName() + "余额不足,不能进行取钱");
            return;
        }
        try {
            Thread.sleep(1000);//放大问题的发生性
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //卡内金额 = 余额-你的钱
        account.money = account.money - drawingMoney;
        //你手里的钱
        nowMoney = nowMoney + drawingMoney;
        System.out.println(account.cardName + "余额为:" + account.money);
        //this.getName()==Thread.currentThread().getName()
        System.out.println(this.getName() + "手里的钱:" + nowMoney);
    }
}
//线程不安全的集合
public class Demo26_UnsafeList {
    public static void main(String[] args) {
        List list = new ArrayList();
        for (int i = 0; i < 1000; i++) {
            new Thread(()->{
                list.add(Thread.currentThread().getName());
            }).start();
        }
        System.out.println(list.size());
    }
}
3.同步方法
  • 由于我们可以通过private关键字来保证数据对象智能被方法访问,所以我们只需针对方法提出一套机制,这套机制就是synchronized关键字,他包括两种方法,他包括两种方法,synchronized和synchronized块
  • synchronized方法控制对”对象的访问",每个对象对应一把锁,每个对象对应一把锁,每个synchronized方法必须调用该方法的对象锁才能进行,否则线程则会阻塞,方法一但执行,就独占该锁,知道该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行
public class UnsafeBuyTicket {

    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket,"小明").start();
        new Thread(buyTicket,"小红").start();
        new Thread(buyTicket,"黄牛").start();
    }
}

class BuyTicket implements Runnable{

    //票
    private int tickNums = 10;
    boolean flag = true;  //外部控制停止方式
    @Override
    public void run() {
        //买票
        while (flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private synchronized void buy() throws InterruptedException {
        //判断是否有票
        if (tickNums<=0){
            flag = false;
            return;
        }
        //模拟演示

        Thread.sleep(100);

        //买票
        System.out.println(Thread.currentThread().getName()+"拿到了"+tickNums--);
    }
}
4.同步块

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7nhW27Ab-1634697367860)(C:Users86150AppDataRoamingTyporatypora-user-imagesimage-20211018212228713.png)]

锁的对象就是变量的量,需要增删改查的对象

案例:

public class UnsafeBuyTicket {

    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket,"小明").start();
        new Thread(buyTicket,"小红").start();
        new Thread(buyTicket,"黄牛").start();
    }
}

class BuyTicket implements Runnable{

    //票
    private int tickNums = 10;
    boolean flag = true;  //外部控制停止方式
    @Override
    public void run() {
        //买票
        while (flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private synchronized void buy() throws InterruptedException {
        //判断是否有票
        if (tickNums<=0){
            flag = false;
            return;
        }
        //模拟演示

        Thread.sleep(100);

        //买票
        System.out.println(Thread.currentThread().getName()+"拿到了"+tickNums--);
    }
}
public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account(100,"结婚基金");

        Drawing you = new Drawing(account,50,"你");
        Drawing me = new Drawing(account,100,"我");

        you.start();
        me.start();
    }
}

//账户
class Account{
    int money;
    String name;

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

//银行
class Drawing extends Thread{

    Account account; //账户
    //取了多少钱
    int drawingMoney;
    //现在手里还有多少钱
    int nowMoney;

    public Drawing(Account account,int drawingMoney,String name){
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    @Override
    public void run() {
        //加锁实现  加锁的是变化的量
        synchronized (account){
            //判断是否有钱
            if (account.money-drawingMoney<0){
                System.out.println(Thread.currentThread().getName()+"钱不够,不能取钱");
                return;
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //卡内余额 = 金额 - 你取的钱
            account.money = account.money - drawingMoney;
            nowMoney = nowMoney + drawingMoney;

            System.out.println(account.name + "的余额为"+account.money);

            System.out.println(this.getName()+"手里的钱为"+nowMoney);
        }
    }
}
public class UnsafeList {

    public static void main(String[] args) throws InterruptedException {
        List list = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            new Thread(()->{
                synchronized(list){
                    list.add(Thread.currentThread().getName());
                }
            }).start();
        }

        Thread.sleep(10);
        System.out.println(list.size());
    }
}
9.线程通信


9.1线程通信问题的解决

public class Demo33_ThreadPC {
    public static void main(String[] args) {
        SynContainer synContainer = new SynContainer();
        new Producer(synContainer).start();
        new Consumer(synContainer).start();
    }
}

//生产者
class Producer extends Thread {
    //容缓冲区
    SynContainer container;

    public Producer(SynContainer container) {
        this.container = container;
    }

    //生产
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            container.push(new Product(i));
            System.out.println("生产了" + i + "件产品");
        }
    }
}

//消费者
class Consumer extends Thread {
    //容缓冲区
    SynContainer container;

    public Consumer(SynContainer container) {
        this.container = container;
    }

    //消费
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了-->" + container.pop().id + "件产品");
        }
    }
}

//产品
class Product {
    int id;//产品编号

    public Product(int id) {
        this.id = id;
    }
}

//缓冲区
class SynContainer {
    //需要一个容器大小
    Product[] products = new Product[10];
    //容器计数器
    int count = 0;

    //生产者放入产品
    public synchronized void push(Product product) {
        //如果容器满了,需要等待消费者消费
        
        while (count == products.length) {
            //通知消费者消费,等待生产
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果没有满,需要丢入产品
        products[count] = product;
        count++;
        //通知消费者消费
        this.notifyAll();
    }

    //消费者消费产品
    public synchronized Product pop() {
        //判断是否能消费
        while (count <= 0) {
            //等待生产者生产
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果可以消费
        count--;
        Product product = products[count];
        //吃完了 通知生产者生产
        this.notifyAll();
        return product;
    }
}

public class Demo33_ThreadPC {
    public static void main(String[] args) {
        SynContainer synContainer = new SynContainer();
        new Producer(synContainer).start();
        new Consumer(synContainer).start();
    }
}

//生产者
class Producer extends Thread {
    //容缓冲区
    SynContainer container;

    public Producer(SynContainer container) {
        this.container = container;
    }

    //生产
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            container.push(new Product(i));
            System.out.println("生产了" + i + "件产品");
        }
    }
}

//消费者
class Consumer extends Thread {
    //容缓冲区
    SynContainer container;

    public Consumer(SynContainer container) {
        this.container = container;
    }

    //消费
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了-->" + container.pop().id + "件产品");
        }
    }
}

//产品
class Product {
    int id;//产品编号

    public Product(int id) {
        this.id = id;
    }
}

//缓冲区
class SynContainer {
    //需要一个容器大小
    Product[] products = new Product[10];
    //容器计数器
    int count = 0;

    //生产者放入产品
    public synchronized void push(Product product) {
        //如果容器满了,需要等待消费者消费
        
        while (count == products.length) {
            //通知消费者消费,等待生产
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果没有满,需要丢入产品
        products[count] = product;
        count++;
        //通知消费者消费
        this.notifyAll();
    }

    //消费者消费产品
    public synchronized Product pop() {
        //判断是否能消费
        while (count <= 0) {
            //等待生产者生产
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果可以消费
        count--;
        Product product = products[count];
        //吃完了 通知生产者生产
        this.notifyAll();
        return product;
    }
}
10.线程池


//测试线程池
public class Demo35_ThreadPool {
    public static void main(String[] args) {
        // 1. 创建服务,擦行间线程池
        // newFixedThreadPool(线程池大小)
        ExecutorService service = Executors.newFixedThreadPool(10);
        //执行
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        //关闭连接
        service.shutdown();
    }
}

class MyThread implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/340949.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号