多线程

多线程

1.1、继承Thread类实现多线程

//创建线程方式一:继承Thread类,重写run()方法,调用start()方法开启线程
public class TestThread extends Thread {
    @Override
    public void run() {
        //run方法线程体
        for (int i = 1; i <= 10; i++) {
            System.out.println("我在写代码----"+i);
        }
    }
    public static void main(String[] args) {
        //主线程
        //创建一个线程对象
        TestThread testThread=new TestThread();
        //调用start方法,主线程和子线程交替执行
        //注:线程开启不一定立即执行,由CPU调度执行
        testThread.start();
        for (int i = 1; i <= 2000; i++) {
            System.out.println("我在学习Java---"+i);
        }
    }
}


1.2、实现Runnable接口开启多线程

//创建线程方式二:实现Runnable接口,重写run()方法,执行线程需要丢入Runnable接口实现类,调用start()方法开启线程
//注:因为java单继承的局限性,推荐使用Runnable
public class TestRunnable implements Runnable {
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("我在听歌---"+i);
        }
    }

    public static void main(String[] args) {
        //创建Runnable接口实现类对象
        TestRunnable testRunnable=new TestRunnable();
        //创建代理类对象
        Thread t=new Thread(testRunnable);
        t.start();
        for (int i = 1; i <= 2000; i++) {
            System.out.println("我在学习英语---"+i);
        }
    }
}


1.3、多线程并发

//多线程并发
public class TestThread01 implements Runnable {
    //票数
    private int ticketNums=20;
    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) {
        //多个线程使用同一对象
        //问题:线程不安全,数据紊乱
        TestThread01 testTicket=new TestThread01();
        new Thread(testTicket,"小华").start();
        new Thread(testTicket,"杰杰").start();
        new Thread(testTicket,"丽丽").start();
    }
}

1.4、多线程模拟龟兔赛跑

public class Race implements Runnable {
    private static String winner;

    public void run() {
        for (int i = 0; i <= 100; i++) {
            if (Thread.currentThread().getName().equals("兔子") && i % 10 == 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            boolean flag = gameOver(i);
            if (flag) {
                break;
            }
            System.out.println(Thread.currentThread().getName() + "-->跑了" + i + "米");
        }
    }

    private boolean gameOver(int step) {
        if (winner != null) {
            return true;
        }
        if (step >= 100) {
            winner = Thread.currentThread().getName();
            System.out.println("获胜者是" + winner);
            return true;
        }
        return false;
    }

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

1.5、实现Callable接口开启多线程

import java.util.concurrent.*;

//线程创建方式三:实现Callable接口
//Callable接口的优点:1.可以定义返回值 2.可以抛出异常
public class TestCallable implements Callable {
    public Boolean call(){
        for (int i = 0; i < 20; i++) {
            System.out.println("我在跑步--"+i);
        }
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable testCallable=new TestCallable();
        //创建执行服务
        ExecutorService service= Executors.newFixedThreadPool(3);
        //提交执行
        Future<Boolean> result=service.submit(testCallable);
        //获取结果
        boolean rs1=result.get();
        //关闭服务
        service.shutdownNow();
    }
}

1.6、静态代理

//结婚模拟静态代理
//真实对象和代理对象都要实现同一个接口
//静态代理的优点:1.代理对象可以完成许多真实对象不能完成的事
 //              2.真实对象专注做自己的事
public class StaticProxy {
    public static void main(String[] args) {
        You you = new You();//目标对象
        WeddingCompany weddingCompany=new WeddingCompany(you);
        weddingCompany.marry();
    }
}
interface Marry{
    void marry();
}
//真实角色,你要结婚
class You implements Marry{
    public void marry() {
        System.out.println("结婚真开心");
    }
}
//代理角色,如婚庆公司
class WeddingCompany implements Marry{
    private Marry target;
    public void marry() {
     before();
     this.target.marry();//真实对象
     after();
    }

    public WeddingCompany(Marry target) {
        this.target = target;
    }
    //结婚前
    private void before(){
        System.out.println("结婚前,布置现场");
    }
    //结婚后
    private void after(){
        System.out.println("结婚后,结清尾款");
    }
}

1.7、Lambda表达式

//推导Lambda表达式
//Lambda表达式的优点: 1.避免匿名内部类定义过多
//                   2.代码简洁
//                   3.去掉了一堆没有意义的代码,只留下核心的逻辑

public class TestLambda {
    //3.静态内部类
    static class Like2 implements ILike{
        public void lambda() {
            System.out.println("我喜欢lambda2");
        }
    }
    public static void main(String[] args) {
        ILike like=new Like();
        like.lambda();
        like=new Like2();
        like.lambda();
        //4.局部内部类
        class Like3 implements ILike{
            public void lambda() {
                System.out.println("我喜欢lambda3");
            }
        }
        like=new Like3();
        like.lambda();
        //5.匿名内部类(没有类的名称,必须借助接口或者父类)
        like=new ILike() {
            public void lambda() {
                System.out.println("我喜欢lambda4");
            }
        };
        like.lambda();
        //6.用lambda简化
        like=()-> {
            System.out.println("我喜欢lambda5");
        };
        like.lambda();

    }
}
//1.定义一个函数式接口(只有一个抽象方法的接口为函数式接口)
interface ILike{
    void lambda();//注:默认为抽象方法
}
//2.实现类
class Like implements ILike{
    public void lambda() {
        System.out.println("我喜欢lambda");
    }
}

import java.util.Random;
//lambda简化实现
public class TestLambda02 {
    public static void main(String[] args) {
//        ILove love=(int a)->{
//            System.out.println("爱心值:"+a);
//        };
//        love.love(100);

        //lambda表达式简化1:去掉参数类型
        ILove love=(a)->{
            System.out.println("爱心值:"+a);
        };
        love.love(100);
        //lambda表达式简化2:去掉括号
        love=a->{
            System.out.println("爱心值:"+a);
        };
        love.love(101);
        //lambda表达式简化3:去掉花括号
        love=a-> System.out.println("爱心值:"+a);
        love.love(102);
        //总结:1.lambda表达式只能在只有一行代码的情况下才能被简化为一行,如果有多行,需要用代码块(花括号)包围
        //     2.必须是函数式接口
        //     3.多个参数也可以去掉参数类型,但是必须要加上括号
    }
}
interface ILove{
    void love(int a);
}

1.8、线程状态

在这里插入图片描述

线程停止

//测试线程停止
//1.建议线程正常停止-->利用次数,不建议死循环
//2.建议设置一个标识位
//3.不要使用stop、destroy等过时或JDK不建议使用的方法
public class TestStop implements Runnable {
    //设置标识位
    private boolean flag=true;

    @Override
    public void run() {
      while (flag){
          int i=0;
          System.out.println("线程正在运行-->"+i++);
      }
    }
    //设置公开的方法停止线程,转换标识位
    public void stop(){
      this.flag=false;
    }
    public static void main(String[] args) {
     TestStop testStop=new TestStop();
     new Thread(testStop).start();
        for (int i = 0; i < 100; i++) {
            System.out.println("主线程正在运行"+i);
            if(i==99){
                //调用stop方法,让线程停止
                testStop.stop();
                System.out.println("线程停止了");
            }
        }
    }
}

线程休眠

import java.text.SimpleDateFormat;
import java.util.Date;

//模拟计时器
public class TestSleep02 implements Runnable {

    @Override
    public void run() {

    }

    //十秒计时器
    public static void tenDown() throws InterruptedException {
        int num = 10;
        while (true) {
            Thread.sleep(1000);//线程休眠
            System.out.println(num--);
            if (num <= 0) {
                System.out.println("线程停止");
                break;
            }
        }
    }

    public static void main(String[] args) {
        Date nowTime = new Date(System.currentTimeMillis());//获取当前系统时间
        while (true){
            try {
                Thread.sleep(1000);
                System.out.println(new SimpleDateFormat("HH:mm:ss").format(nowTime));
                nowTime=new Date(System.currentTimeMillis());//更新当前时间
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

线程礼让

//测试线程礼让
//礼让不一定成功,看CPU心情
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()+"线程结束");
    }
}

线程强制执行join

//测试Join,可以理解为插队
public class TestJoin implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 500; i++) {
            System.out.println("join来插队了"+i);
        }
    }

    public static void main(String[] args) {
        //启动线程
        TestJoin testJoin = new TestJoin();
        Thread thread=new Thread(testJoin);
        thread.start();
        //主线程
        for (int i = 0; i < 1000; i++) {
            if(i==500){
                try {
                    thread.join();//join插队
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("主线程"+i);
        }
    }
}

观察线程的状态

//测试线程的状态
public class TestState {
    public static void main(String[] args) {
        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();//Run
        while (state != Thread.State.TERMINATED) {//只要线程不终止,一直输出状态
            try {
                Thread.sleep(100);
                state = thread.getState();//更新线程状态
                System.out.println(state);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }
}

1.9、线程的优先级

//测试线程的优先级
public class TestPriority {
    public static void main(String[] args) {
        //主线程默认优先级为5
        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);
        //先设置优先级再启动
        //优先级高,CPU调度高
        //优先级低,CPU调度低,但并不是调度低就不会被调用
        t1.start();

        t2.setPriority(1);
        t2.start();

        t3.setPriority(4);
        t3.start();

        t4.setPriority(Thread.MAX_PRIORITY);//默认值Thread.MAX_PRIORITY=10
        t4.start();

        t5.setPriority(3);
        t5.start();

        t6.setPriority(7);
        t6.start();
    }

}
class MyPriority implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
    }
}

2.0、守护线程

//线程分为用户线程和守护线程
//测试守护线程
//注:虚拟机必须确保用户线程执行完毕,虚拟机不用等待守护线程执行完毕
public class TestDaemon {
    public static void main(String[] args) {
        God god = new God();
        I i = new I();
        Thread thread=new Thread(god);
        thread.setDaemon(true);//默认为false表示用户线程,正常的线程都是用户线程
        thread.start();
        new Thread(i).start();//我  用户线程启动
    }

}
//上帝
class God implements Runnable{
    @Override
    public void run() {
        while (true){
            System.out.println("上帝保佑着你");
        }
    }
}
//我
class I implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 36500; i++) {
            System.out.println("我一生都很开心的活着");
        }
        System.out.println("======goodbye! world!=======");
    }
}

2.1、线程同步机制

三大不安全的案例

//不安全的买票
//线程不安全,会出现负数
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 ticketNums=10;
    boolean flag=true;//外部停止方式
    @Override
    public void run() {
     //买票
        while (flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    private 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(100,"创业基金");
        Drawing you=new Drawing(account,50,"你");
        Drawing girlFriend=new Drawing(account,100,"女朋友");
        you.start();
        girlFriend.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=new Account(100,"你");//账户
    int drawingMoney;//取了多少钱
    int nowMoney;//现在手里有多少钱
    public Drawing(Account account,int drawingMoney,String name){
        super(name);
        this.drawingMoney=drawingMoney;
        this.nowMoney=nowMoney;
    }

    @Override
    //取钱
    public void run() {
        //判断有没有钱
       if(account.money-drawingMoney<0){
           System.out.println(Thread.currentThread().getName()+"余额不足,无法取钱");
           return;
       }
       //卡内余额=余额-取钱金额
        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);
    }
}

import java.util.ArrayList;
import java.util.List;

//不安全的线程集合
//数据变少
public class UnsafeList {
    public static void main(String[] args) {
        List<String> list=new ArrayList<String>();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
             list.add(Thread.currentThread().getName());
            }).start();
        }
        System.out.println(list.size());
    }
}

使用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 ticketNums=10;
    boolean flag=true;//外部停止方式
    @Override
    public void run() {
     //买票
        while (flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //synchronized同步方法,锁的是this
    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 girlFriend=new Drawing(account,100,"女朋友");
        you.start();
        girlFriend.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;
        this.nowMoney=nowMoney;
    }

    @Override
    //取钱
    //synchronized的默认值是this,锁的对象就是变化的量
    public void run() {
        //判断有没有钱
        synchronized (account){
            if(account.money-drawingMoney<0){
                System.out.println(Thread.currentThread().getName()+"余额不足,无法取钱");
                return;
            }
            //卡内余额=余额-取钱金额
            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);
        }
    }
}

import java.util.ArrayList;
import java.util.List;

//不安全的线程集合
//数据变少
public class UnsafeList {
    public static void main(String[] args) {
        List<String> list=new ArrayList<String>();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                   synchronized (list) {
                       list.add(Thread.currentThread().getName());
                   }
            }).start();
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }
}

JUC并发

import java.util.concurrent.CopyOnWriteArrayList;

public class TestJUC {
    public static void main(String[] args) {
        CopyOnWriteArrayList<String> list=new CopyOnWriteArrayList<String>();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
             list.add(Thread.currentThread().getName());
            }).start();
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }
   
   
}

死锁探究

在这里插入图片描述

  • 死锁案例
//死锁:多个线程抱着对方的需要的资源,然后形成僵持,导致程序卡死
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 Mirror mirror=new Mirror();
    static Lipstick lipstick=new Lipstick();
    int choice;//选择
    String girlName;//女孩的姓名
    public 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+"获得口红的锁");
                }
            }
        }
    }
}

解除死锁之后的代码

//死锁:多个线程抱着对方的需要的资源,然后形成僵持,导致程序卡死
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 Mirror mirror=new Mirror();
    static Lipstick lipstick=new Lipstick();
    int choice;//选择
    String girlName;//女孩的姓名
    public 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+"获得口红的锁");
            }
        }
    }
}

Lock锁
在这里插入图片描述

测试Lock锁

import java.util.concurrent.locks.ReentrantLock;

//测试Lock锁
public class TestLock {
    public static void main(String[] args) {
        TestLock2 testLock2 = new TestLock2();
        new Thread(testLock2).start();
    }
}

class TestLock2 implements Runnable {
    @Override
    public void run() {
        int ticketNums = 10;
        //定义Lock锁
        final ReentrantLock lock = new ReentrantLock();

        while (true) {
            try {
                lock.lock();//加锁
                if (ticketNums > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(ticketNums--);
                } else {
                    break;
                }

            } finally {
                //解锁
                lock.unlock();
            }
        }
    }
}

synchronized和lock的区别

  • synchronized是一个Java的关键字,而Lock是一个类
  • synchronized无法获取锁的状态,而Lock可以去判断是否获取到了锁
  • synchronized执行完后会自动释放锁,而Lock需要手动去释放,如果没有释放锁,就会造成死锁的现象
  • synchronized:线程A获取到了锁,这时候线程B只能慢慢等待;Lock:不一定会一直等待(Lock.trylock();)
  • synchronized:可重入锁,非公平,不可中断;Lock:可重入锁,可以设置公平和非公平,可判断
  • synchronized适合锁少量的同步代码,Lock适合锁大量的同步代码

2.2、线程通信

在这里插入图片描述

管程法

//测试生产者消费者模型-->利用缓冲区解决:管程法
//需要四个对象:生产者、消费者、产品、缓冲区
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;
    }
}

信号灯法

//测试生产者消费者模型-->利用标志位解决:信号灯法
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 {
    //演员表演,观众等待
    //观众观看,演员等待
    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;

    }

}

2.3、线程池

测试线程池

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

//测试线程池
public class TestPool {
    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());
        //2.关闭连接
        service.shutdown();
    }
}

class MyThread implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值