Java基础学习-----多线程、锁(完更,后续会继续补充)

lambda表达式可以先看一下
参考地址:https://blog.csdn.net/weixin_43417252/article/details/106233782
jdk8新特性,避免匿名内部类定义过多,任何接口如果只包含一个抽象方法,那么他就是一个函数是接口。对于函数式接口,我们可以直接通过lambda表达式来创建接口对象。
此博客练习源代码下载地址:https://github.com/chengYang-ape/ThreadDemo

一、线程

基本概念:

  • 任务:比如一个人吃饭玩手机,开车打电话,就做了两个任务。本质:同一时间只做了一件事情。
  • 进程:在操作系统中运行的程序就是进程,一个进程里可以跑很多线程。IDE,qq,播放器等。
  • 多线程:为了提高效率,公路上面设计有好多车道,好多车可以并行走。
    在这里插入图片描述
    线程创建方式:
    三种创建方式:继承Thread类,实现Runnable接口,实现Callable接口。
    继承Thread类:
    第一步继承Thread类,调用start方法。
//创建线程方式一:继承Thread类,重写run方法。
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线程,主线程
        //创建一个线程,调用start方法。
        TestThread1 testThread1 = new TestThread1();
        testThread1.start();
        for (int i = 0; i < 2000; i++) {
            System.out.println("我在学习多线程--" + i);
        }
    }
}

注意:调用start方法,是交替执行,run方法体中输出的句子是夹杂在主线程输出句子的中间。
继承Thread类调用run方法

//创建线程方式一:继承Thread类,重写run方法。
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线程,主线程
        //创建一个线程,调用start方法。
        TestThread1 testThread1 = new TestThread1();
        testThread1.run();
        for (int i = 0; i < 2000; i++) {
            System.out.println("我在学习多线程--" + i);
        }
    }
}

注意:先输出run方法的语句,然后在走主线程。
练习小例子:
创建一个多线程,下载网络图片,用start方法,下载的图片顺序不固定,也说明了是交替执行。
注意: 先导入commons IO包,切记包一定要导入成功,不能有错。url可以自己随意找,一定要有网。代码如下:

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

//练习Thread,实现多线程同步下载图片。
public class TestThread2 extends Thread{
    private String url;  //图片地址
    private String name;   //保存的文件名

    public TestThread2(String url,String name){
        this.url = url;
        this.name = name;
    }
    @Override
    public void run() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url,name);
        System.out.println("下载了文件名为:" + name);
    }
    public static void main(String[] args) {
        TestThread2 t1 = new TestThread2("https://img-blog.csdnimg.cn/20200517131520779.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzQxNzI1Mg==,size_16,color_FFFFFF,t_70","1.jpg");
        TestThread2 t2 = new TestThread2("https://img-blog.csdnimg.cn/20200517131520779.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzQxNzI1Mg==,size_16,color_FFFFFF,t_70","2.jpg");
        TestThread2 t3 = new TestThread2("https://img-blog.csdnimg.cn/20200517131520779.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzQxNzI1Mg==,size_16,color_FFFFFF,t_70","3.jpg");
        t1.start();
        t2.start();
        t3.start();
    }
}
class WebDownloader{
    public void downloader(String url,String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常,downloader方法出现问题");
        }
    }
}

实现Runnable接口:
使用的是代理模式。

//创建线程方式二:实现runnable接口,重写run方法,调用start方法。
public class TestThread3 implements Runnable{
    @Override
    public void run() {
        //run方法线程体
        for (int i = 0; i < 20; i++) {
            System.out.println("我在看代码---" + i);
        }
    }
    public static void main(String[] args) {
        //创建Runnable接口的实现类对象
        TestThread3 testThread3 = new TestThread3();
        //创建线程对象,通过线程对象开启我们的线程,代理模式。
        //Thread thread = new Thread(testThread3);
        //thread.start();

        //上面两句可以简写
        new Thread(testThread3).start();
        for (int i = 0; i < 1500; i++) {
            System.out.println("我在学习多线程--" + i);
        }
    }
}

可以试着下载图片的小练习换成Runnable接口实现。

并发问题:

模拟抢票,会出现拿到同一张票,或者拿到0张票,如果不解决会出现问题,这是一个有问题的程序,主要是了解并发。

//多个线程同时操作同一个对象,买火车票的例子
public class TestThread4 implements Runnable {
    private int ticketNums = 10;

    @Override
    public void run() {
        while (true){
            if (ticketNums <= 0){
                break;
            }
            System.out.println(Thread.currentThread().getName() + "--->拿到了第" + ticketNums-- + "张票");
        }
    }
    public static void main(String[] args) {
        TestThread4 testThread4 = new TestThread4();
        new Thread(testThread4,"小明").start();
        new Thread(testThread4,"老师").start();
        new Thread(testThread4,"黄牛").start();
    }
}

模拟龟兔赛跑:

//模拟龟兔赛跑
public class Race implements Runnable {
    private static String winner;

    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            //模拟兔子休息
            if (Thread.currentThread().getName().equals("兔子") && i%10 == 0){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            boolean flag = gameOver(i);
            if (flag){
                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();
    }
}

实现Callabel接口
实现Callable接口实现网络图片下载,注意导入commons包。

package com.yang.demo02;

import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;


//线程创建方式三:实现Callable接口。
public class TestCallable implements Callable<Boolean> {
    private String url;  //图片地址
    private String name;   //保存的文件名

    public TestCallable(String url,String name){
        this.url = url;
        this.name = name;
    }
    @Override
    public Boolean call() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url,name);
        System.out.println("下载了文件名为:" + name);
        return true;
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1 = new TestCallable("https://img-blog.csdnimg.cn/20200517131520779.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzQxNzI1Mg==,size_16,color_FFFFFF,t_70","1.jpg");
        TestCallable t2 = new TestCallable("https://img-blog.csdnimg.cn/20200517131520779.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzQxNzI1Mg==,size_16,color_FFFFFF,t_70","2.jpg");
        TestCallable t3 = new TestCallable("https://img-blog.csdnimg.cn/20200517131520779.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzQxNzI1Mg==,size_16,color_FFFFFF,t_70","3.jpg");

        //创建执行服务:
        ExecutorService ser = Executors.newFixedThreadPool(3);

        //提交执行
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t2);
        Future<Boolean> r3 = ser.submit(t3);

        //获取结果:
        boolean rs1 = r1.get();
        boolean rs2 = r2.get();
        boolean rs3 = r3.get();

        //关闭服务
        ser.shutdownNow();

    }
}
class WebDownloader{
    public void downloader(String url,String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常,downloader方法出现问题");
        }
    }
}

线程状态:
在这里插入图片描述
线程方法:
在这里插入图片描述

  • 线程停止
    测试停止线程
    1.建议线程正常停止—>利用次数,不建议死循环
    2.建议使用标志位—>设置一个标识位
    3.不要使用stop、destroy或者JDK不建议的方法
public class TestThreadStop 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) {
        TestThreadStop testThreadStop = new TestThreadStop();
        new Thread(testThreadStop).start();

        for (int i = 0; i < 2000; i++) {
            System.out.println("main..." + i);
            if (i == 800){
                //3.调用stop方法。
                testThreadStop.stop();
                System.out.println("线程该停止了");
            }
        }
    }
}
  • 线程休眠
    sleep指定当前线程阻塞的毫秒数;
    sleep存在异常InterruptedException;
    sleep时间到达后线程进入就绪状态;
    sleep可以模拟网络延时,倒计时等;
    每一个对象都有一个锁,sleep不会释放锁。

模拟网络延时

public class TestSleep 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) {
        TestSleep testSleep = new TestSleep();
        new Thread(testSleep,"小明").start();
        new Thread(testSleep,"老师").start();
        new Thread(testSleep,"黄牛").start();
    }
}

模拟倒计时

//模拟倒计时
public class TestSleep2 {
    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();
            }
        }
    }
    /*//模拟倒计时
    public static void main(String[] args) {
        try {
            tenDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }*/
    public static void tenDown() throws InterruptedException {
        int num = 10;
        while (true){
            Thread.sleep(1000);
            System.out.println(num--);
            if (num <= 0){
                break;
            }
        }
    }
}
  • 线程礼让
    让当前正在执行的程序暂停 ,但不阻塞;
    让线程的运行状态进入就绪状态;
    让cpu重新调度,礼让不一定成功。如A线程正在执行,B线程在就绪,A线程执行礼让方法,A,B都就绪,看系统调配,不一定哪个执行。
//测试礼让线程
public class TestYield {
    public static void main(String[] args) {
        MyYield myYield = new MyYield();
        
        new Thread(myYield,"a").start();
        new Thread(myYield,"b").start();
    }
}
class MyYield implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "线程开始执行");
        Thread.yield();   //礼让
        System.out.println(Thread.currentThread().getName() + "线程停止执行");
    }
}

a线程先执行,a结束b开始运行—>礼让失败;
如果a执行,切换为b执行,b先结束然后a结束—>礼让成功

  • 线程插队Join
    Join合并线程,待此线程执行完之后,在执行其他线程,其他线程阻塞。可以想象成插队。
//join方法
public class TestJoin implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("线程vip来了--->" + i);
        }
    }
    public static void main(String[] args) throws InterruptedException {
        TestJoin testJoin = new TestJoin();
        Thread thread = new Thread(testJoin);
        thread.start();

        //主线程
        for (int i = 0; i < 1000; i++) {
            if (i == 200){
                thread.join();
            }
            System.out.println("main" + i);
        }
    }
}
  • 线程状态观测在这里插入图片描述
//观察线程状态
public class TestState {

    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);  //new
        
        //观察启动后
        thread.start();//启动线程
        state = thread.getState();
        System.out.println(state);

        while (state != Thread.State.TERMINATED){ //只要线程不终止就一直输出状态
            Thread.sleep(100);
            state = thread.getState();  //更新线程状态
            System.out.println(state);  //输出状态
        }
    }
}
  • 线程的优先级
    Java提供一个线程调度器来检测控制程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。
    线程的优先级用数字表示,范围是1~10
    Thread.MIN_PRIORITY = 1;
    Thread.MAX_PRIORITY = 10;
    Thread.NORM_PRIORITY = 5;
    使用getPriority().setPriority(int XXX)
//测试线程的优先级
public class TestPriority {
    public static void main(String[] args) {
        //主线程的优先级:默认
        System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());

        MyPriority myPriority = new MyPriority();
        Thread t1 = new Thread(myPriority);
        Thread t2 = new Thread(myPriority);
        Thread t3 = new Thread(myPriority);
        Thread t4 = new Thread(myPriority);
        Thread t5 = new Thread(myPriority);
        Thread t6 = new Thread(myPriority);

        //设置优先级在启动
        t1.start();

        t2.setPriority(Thread.MAX_PRIORITY);
        t2.start();

        t3.setPriority(3);
        t3.start();

        t4.setPriority(2);
        t4.start();

        t5.setPriority(1);
        t5.start();

        t6.setPriority(6);
        t6.start();
    }
}
class MyPriority implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
    }
}
  • 守护线程
    线程分为守护线程和用户现场;
    虚拟机必须确保用户现场执行完毕;
    虚拟机不用等待守护线程执行完毕;
    守护线程如:垃圾回收,操作日志,内存监控等。
//测试守护线程,上帝守护你的举例
public class TestDaemon {
    public static void main(String[] args) {
        God god = new God();
        You you = new You();

        Thread thread = new Thread(god);
        thread.setDaemon(true);  //默认是false 是用户线程

        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======");
    }
}

God是守护线程,而You是用户线程,当you线程结束之后,God随后也结束,不是一直循环下去。

2、线程同步

多线程操作同一个资源,也就是并发问题抢票取钱问题。这时候就要了解一下锁了。在这里插入图片描述在这里插入图片描述
买票的时候加同步方法:

//不安全的买票,运行之后有负数
//同步之后
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();
        new Thread(station,"wo").start();
        new Thread(station,"ni").start();
        new Thread(station,"牛牛").start();
    }
}
class BuyTicket implements Runnable{
    //定义票
    private int ticketNums = 10;
    boolean flag = true;

    @Override
    public void run() {
        //买票
        while(flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //synchronized 同步方法
    private synchronized void buy() throws InterruptedException {
        //判断是否有票
        if (ticketNums <= 0){
            flag = false;
            return;
        }
        //模拟延时
        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName() + "拿到第" + ticketNums-- + "张票");
    }
}

取钱的时候加同步:
锁的对象要是变量,增删改的量,注意锁的地方;

//不安全的取钱
public class UnsafeBank {

    public static void main(String[] args) {
        Account account = new Account(1000,"结婚基金");
        Drawing you = new Drawing(account,50,"你");
        Drawing girl = new Drawing(account,800,"girl");
        you.start();
        girl.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(40);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //卡内余额 = 余额  - 你取的钱
            account.money = account.money - drawingMoney;
            nowMoney = nowMoney + drawingMoney;

            System.out.println(account.name + "余额为" + account.money);
            //this.getName() = Thread.currentThread().getName()
            System.out.println(this.getName() + "手里的钱" + nowMoney);
        }

    }
}

死锁:
多个线程占用各自一些公共资源,并互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形。某一个同步块拥有两个以上对象的锁时,就可能发生死锁。
在这里插入图片描述
举例:

//多个线程互相抱着对方需要的资源,形成死锁。
public class DeadLock {
    public static void main(String[] args) {
        Makeup g1 = new Makeup(0,"小红帽");
        Makeup g2 = new Makeup(1,"灰姑娘");
        g1.start();
        g2.start();
    }
}

//口红
class Lipstick{
}
//镜子
class Mirror{
}

class Makeup extends Thread{

    //需要的资源只有一份,用static保证只有一份
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    int choice; //选择
    String girlName; //使用者的名字

    Makeup(int choice,String girlName){
        this.choice = choice;
        this.girlName = girlName;

    }
    @Override
    public void run() {
        //化妆
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //化妆,互相持有对方的锁,需要拿到对方的资源
    private void makeup() throws InterruptedException {
        if (choice ==0){
            synchronized (lipstick){  //获得口红的锁
                System.out.println(this.girlName + "获得口红的锁");
                Thread.sleep(1000);
                synchronized (mirror){   //想要一秒后获得镜子的锁
                    System.out.println(this.girlName + "获得镜子的锁");
                }
            }
        }else {
            synchronized (mirror){  //获得镜子的锁
                System.out.println(this.girlName + "获得镜子的锁");
                Thread.sleep(2000);
                synchronized (lipstick){   //想要一秒后获得镜子的锁
                    System.out.println(this.girlName + "获得口红的锁");
                }
            }
        }
    }
}

解决方法:把锁的地方放到同步代码块外面,不要锁中锁;修改makeup方法的同步代码块为如下图所示。

    //化妆,互相持有对方的锁,需要拿到对方的资源
    private void makeup() throws InterruptedException {
        if (choice ==0){
            synchronized (lipstick){  //获得口红的锁
                System.out.println(this.girlName + "获得口红的锁");
                Thread.sleep(1000);
                }
            synchronized (mirror){   //想要一秒后获得镜子的锁
                System.out.println(this.girlName + "获得镜子的锁");
            }
        }else {
            synchronized (mirror){  //获得镜子的锁
                System.out.println(this.girlName + "获得镜子的锁");
                Thread.sleep(2000);
                }
            synchronized (lipstick){   //想要一秒后获得镜子的锁
                System.out.println(this.girlName + "获得口红的锁");
            }
        }
    }
}

3、Lock锁

在这里插入图片描述
在这里插入图片描述
还用之前的买票,体会一下lock锁。

public class TestLock {
    public static void main(String[] args) {
        TestLock2 t1 = new TestLock2();
        new Thread(t1).start();
        new Thread(t1).start();
        new Thread(t1).start();
    }
}
class TestLock2 implements Runnable{
    int ticketNums = 10;

    //定义可重复锁
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true){
            try{
                lock.lock();//加锁
                if (ticketNums > 0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() +" 取到 "+ ticketNums-- );
                }else {
                    break;
                }
            }finally {
                //解锁
                lock.unlock();
            }

        }

    }
}

线程协作:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
解决方式一:管程法

在这里插入图片描述

//测试生产者消费者模型--->利用缓冲区解决:管程法
public class TestPC {
    public static void main(String[] args) {
        SynContainer container = new SynContainer();
        new Productor(container).start();
        new Consumer(container).start();
    }
}
//生产者
class Productor extends Thread{
    SynContainer container;

    public Productor(SynContainer container){
        this.container = container;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            container.push(new Chicken(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 Chicken {
    int id; //产品编号

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

//定义缓冲区
class SynContainer{
    //需要一个容器大小
    Chicken[] chickens = new Chicken[10];
    //容器计数器
    int count = 0;
    //生产者放入产品
    public synchronized void push(Chicken chicken){
        //如果容器满了,就需要等待消费者取
        if (count == chickens.length){
            //通知消费者消费,生产等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果没有满,就需要丢入产品
        chickens[count] = chicken;
        count++;
        //可以通知消费者消费了
        this.notifyAll();
    }
    //消费者取出产品
    public synchronized Chicken pop(){
        //判断能否消费
        if (count ==0){
            //通知生产者生产,消费等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果有产品,就可以消费产品
        count--;
        Chicken chicken = chickens[count];

        //吃完了,通知生产者生产
        this.notifyAll();
        return chicken;
    }
}

解决方式二:信号灯发
并发协作模型生产者/消费者模式 -->信号灯法

//测试生产者消费者问题2:信号灯法,标志位解决
public class TestPC2 {
    public static void main(String[] args) {
        TV tv = new TV();

        new Player(tv).start();
        new Watcher(tv).start();
    }
}
// 生产者 -->演员
class Player extends Thread{
    TV tv;
    public Player(TV tv){
        this.tv = tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if (i%2 ==0){
                this.tv.play("喜剧之王");
            }else {
                this.tv.play("大米广告");
            }
        }
    }
}
// 消费者 -->观众
class Watcher extends Thread{
    TV tv;
    public Watcher(TV tv){
        this.tv = tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            tv.watch();
        }
    }
}
// 产品 -->节目
class TV {
    //演员表演,观众等待 T
    //观众观看,演员等待 F
    String voice;//表演的节目
    boolean flag = true;
    //表演
    public synchronized void play(String voice){
        if (!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("演员表演了:" + voice);
        //通知观众观看
        this.notifyAll(); //通知唤醒
        this.voice = voice;
        this.flag = !this.flag;
    }
    //观众看
    public synchronized void watch(){
        if (flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观看了" + voice);
        //通知演员表演
        this.notifyAll();
        this.flag = !this.flag;
    }
}

线程池:
在这里插入图片描述

代码如下:

//测试线程池
public class TestPool {
    public static void main(String[] args) {
        //1.创建服务,创建线程池 参数为池子大小
        ExecutorService service = Executors.newFixedThreadPool(10);
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        //2.关闭连接
        service.shutdown();
    }
}
    
class MyThread implements Runnable{
    @Override
    public void run() {
            System.out.println(Thread.currentThread().getName());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值