多线程

一、线程简介

任务,进程,线程,多线程

1、多任务

本质:在同一时间只做了一件事情

2、多线程

多条线路-->多条路

单线程的效率低,多线程的效率就会高很多。

3、进程

在操作系统中运行的程序就是进程。

程序是指令和数据的有序集合,其本身没有任何运行的概念,是一个静态的概念。

进程是执行程序的一次执行过程,他是一个动态的过程,是资源分配的单位。

一个进程中可以包含若干个线程,当然一个进程中至少包含一个进程。线程是CPU调度和执行的单位。

 

二、线程创建

1、线程创建的三种方式

Thread class -->继承Thread类

Runable ---> 实现Runable接口

Callable接口 ---> 实现Callable接口

1.1、继承Thread类

  1. 继承Thread类

  2. 重写run()方法

  3. 调用start开启线程

复制代码
public class TestThread extends Thread{
    @Override
    public void run() {
        //run方法线程体
        for (int i = 0; i < 10; i++) {
            System.out.println("我在学习多线程"+i);
        }
    }

    public static void main(String[] args) {
        //主方法
        for (int i = 0; i < 10; i++) {
            System.out.println("我在玩手机"+i);
        }

        //创建一个新的线程,用start()方法调用
        TestThread testThread = new TestThread();
        testThread.start();
    }
}
复制代码

两条线程是同时执行。

线程开启不一定立即执行,由CPU执行调度。

1.2、实现Runable接口

  1. 继承Runable接口

  2. 重写run方法

  3. 通过new Thread对象的start()方法执行

复制代码
public class TestRunable implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("我在学习多线程"+i);
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println("我在学习"+i);
        }

        TestThread testThread = new TestThread();

        new Thread(testThread).start();
        
    }
}
复制代码

优点:避免单继承的局限性,灵活方便,方便应用一个对象被多线程使用。

多个线程同事操作同一个对象

复制代码
//买火车票
public class TestDuoXiancheng implements Runnable{

    //火车票
    private int ticktet = 10;

    @Override
    public void run() {
        while (true) {
            if (ticktet <= 0){
                break;
            }
           //延时
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName()+"拿到了第" + ticktet-- + "张票");
        }
    }

    public static void main(String[] args) {
        TestDuoXiancheng testDuoXiancheng = new TestDuoXiancheng();

        new Thread(testDuoXiancheng,"红红").start();
        new Thread(testDuoXiancheng,"黄黄").start();
        new Thread(testDuoXiancheng,"蓝蓝").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;
        }else {
            if (steps == 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.3、实现Callable接口

  1. 实现Callable接口,需要返回值类型

  2. 重写call方法,需要抛出异常

  3. 创建目标对象

  4. 创建执行服务

  5. 提交执行

  6. 获取结果

  7. 关闭服务

2、静态代理模式

复制代码
public class StaticProxy {
    public static void main(String[] args) {
        new Thread(()-> System.out.println("love")).start();
        Wedding wedding = new Wedding(new You());
        wedding.HappyMarry();
    }
}

interface marry{
    void HappyMarry();
}

//真实对象: 你去结婚
class You implements marry{
    @Override
    public void HappyMarry() {
        System.out.println("========Marry=========");
    }
}
//婚庆公司:帮助你结婚
class Wedding implements marry{
   //代理真实代理角色
    private marry target;

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

    @Override
    public void HappyMarry() {
        before();
        this.target.HappyMarry();
        after();
    }

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

    private void after(){
        System.out.println("收拾现场");
    }
}
复制代码

总结:

  • 真实对象和代理对象都需要实现一个接口

  • 代理对象要代理真实角色

好处:

  • 代理对象可以做很多代理角色做不了的事情

  • 真实对象专注自己的事情

3、Lamda表达式

实质属于函数式编程的概念

为什么要使用Lamda表达式?

  • 避免匿名内部类定义过多

  • 让代码更简洁

  • 去掉一些没有意义的代码,留下核心的逻辑

函数式接口的定义:

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

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

三、线程的状态

1、线程的五种状态

1、创建

Thread thread = new Thread()

2、启动

调用start()方法

3、运行

进入运行状态,线程才真正执行线程体的代码

4、阻塞

调用sleep、wait或同步锁定时,进入阻塞状态,阻塞状态事件解除后,重新进入就绪状态,等待cpu调度

5、死亡

线程中断或者死亡,就不能再次启动

2、线程方法

 

3、停止线程

  • stop()、destroy()方法 (ps:不建议使用,已废弃)。

  • 推荐线程自己停止下来,利用次数,不建议死循环。

  • 建议使用一个标志位进行终止变量,当flag=flase,则终止线程运行。

复制代码
public class TestStop implements Runnable{
    //设置标识符
    private Boolean flag = true;
    @Override
    public void run() {
        int i = 0;
        while (flag){
            System.out.println("run=========="+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 < 1000; i++) {
            System.out.println("main============="+i);
            if (i == 900) {
                testStop.stop();
                System.out.println("线程停止");
            }
        }
    }
}
复制代码

4、线程休眠

sleep

模拟延迟

复制代码
//模拟网络延迟:放大问题的发生性
public class TestSleep implements Runnable{

    private int ticktet = 10;

    @Override
    public void run() {
        while (true) {
            if (ticktet <= 0){
                break;
            }

            //模拟延迟
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName()+"拿到了第" + ticktet-- + "张票");
        }
    }

    public static void main(String[] args) {
        TestDuoXiancheng testDuoXiancheng = new TestDuoXiancheng();

        new Thread(testDuoXiancheng,"红红").start();
        new Thread(testDuoXiancheng,"黄黄").start();
        new Thread(testDuoXiancheng,"蓝蓝").start();

    }
}
复制代码

模拟倒计时:

复制代码
//模拟倒计时
public class TestSleep2{
    
    public static void tenDown() throws Exception{
        int num = 10;
        while (true) {
            Thread.sleep(100);
            System.out.println("==============="+num--);
            if (num<=0) {
                break;
            }
        }
    }

    public static void main(String[] args) {
        try {
            tenDown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
复制代码

 

打印系统当前时间:

复制代码
//打印当前系统时间
public static void main(String[] args) {
    //获取系统当前时间
    Date date = new Date(System.currentTimeMillis());

    while (true){
        try {
            Thread.sleep(1000);
            System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
            date = new Date(System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
复制代码

 

5、线程礼让

yield

礼让线程,让当前正在做执行的线程暂停,但不阻塞

将线程从运行状态转为就绪状态

让cpu重新调度,礼让不一定成功,看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()+"线程停止执行");
    }
}
复制代码

 

6、线程强制执行

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) {
        Thread thread = new Thread(new TestJoin());
        thread.start();

        for (int i = 0; i < 1000; i++) {
            if (i == 200){
                try {
                    thread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("main=========="+i);
        }
    }
}
复制代码

 

7、线程观察状态

Thread.State

 

复制代码
public class TestState{
    public static void main(String[] args) throws Exception{
        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);

        //只要线程不终止,就一直输出状态
        while (state != Thread.State.TERMINATED){
            Thread.sleep(100);
            //更新线程状态
            state = thread.getState();
            System.out.println(state);
        }

    }
}
复制代码

当线程停止之后,就不能在启动线程了。

8、线程的优先级(Priority)

Java提供了一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。

线程的优先级用数字标识,范围从1-10。

  • Thread.MIN_PRIORITY = 1;

  • Thread.MAX_PRIORITY = 10;

  • Thread.NORM_PRIORITY = 5;

使用以下方式改变或获取优先级:

setPriority()、getPriority()

测试:

复制代码
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);

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

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

        t3.setPriority(4);
        t3.start();
        
        t4.setPriority(10);
        t4.start();
    }

}

class MyPriority implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"测试线程--->"+Thread.currentThread().getPriority());
    }
}
复制代码

优先级低只意味着获得调度的概率低,并不是优先级低就不会被调用,这都是看CPU的调度。

9、守护线程(daemon)

  • 线程分为守护线程用户线程(main)

  • 虚拟机必须确保用户线程执行完毕

  • 虚拟机不用等待守护线程执行完毕

  • 如:后台记录操作日志,监控内存,垃圾回收等待

测试:

复制代码
//测试:上帝守护你
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);
        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==========");
    }
}
复制代码

 

四、线程同步

发生条件:多个线程操作同一个资源

1、并发

并发:同一个对象被多个线程同时操作。

当处理这样的线程并发问题的时候我们就需要线程同步,可以理解为排队等待,多个需要同事访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程再使用。

2、队列和锁

线程同步的形成条件:队列+锁,可以保证线程的安全性

当同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突的问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized,当一个线程获取到它的排它锁,独占资源,其他线程必须等待,使用后释放锁即可。不过存在一下问题:

  1. 一个线程持有锁,会导致其他所有需要此锁的线程挂起(会影响性能)。

  2. 在多线程竞争的情况下,加锁、释放锁会导致比较多的上下文切换和调度延时,引起性能问题。

  3. 如果一个优先级高的线程等待一个优先级低的线程释放锁,会导致优先级倒置,引起性能问题。

3、同步方法

由于我们可以通过private关键字来保证对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是sybchronized关键字,它包括两种方法:

sybchronized方法和synchronized

同步方法:public sybchronized void method(int args) {}

sybchronized方法控制对“对象”的访问,每个对象应有一把锁,每个sybchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回锁才能释放锁,后面被阻塞的线程才能得到这个锁,继续执行

缺陷:若将一个大的方法申明为sybchronized将会影响效率。

方法里面需要修改的内容才需要锁,锁的太多,浪费资源。

同步块

同步块:sybchronized(Obj){}

Obj称之为同步监视器

  • Obj可以使任何对象,但是推荐使用共享资源作为同步监视器

  • 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者是class

同步监视器的执行过程:

  • 第一个线程访问,锁定同步监视器,执行其中代码

  • 第二个线程访问,发现同步监视器被锁定,无法访问

  • 第一个线程访问完毕,解锁同步监视器

  • 第二个线程访问,发现同步监视器没有锁,然后锁定并访问

测试:

同步方法

复制代码
public class UnSafeBuy {
    public static void main(String[] args) {
        Buytickets station = new Buytickets();

        new Thread(station,"小红").start();
        new Thread(station,"小黄").start();
        new Thread(station,"小蓝").start();
    }
}
class Buytickets implements Runnable{
    private int ticketsNums = 10;
    boolean flag = true;
    @Override
    public void run() {
        //买票
        while (flag){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            buy();
        }
    }

    //`sybchronized`同步方法,所得是this
    public synchronized void buy() {
        //判断是否有票
        if (ticketsNums <= 0) {
            flag = false;
            return;
        }

        //买票
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketsNums--);
    }
}
同步方法
复制代码

 

同步块:

复制代码
public class Hotil {
    public static void main(String[] args) {
        Account account = new Account(100,"make");
        Drawing you = new Drawing(account, 50, "you");
        Drawing wife = new Drawing(account, 50, "wife");

        you.start();
        wife.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;
            }

            account.money = account.money - drawingMoney;
            nowMoney = nowMoney + drawingMoney;

            System.out.println(account.name + "余额为:" + account.money);
            System.out.println(this.getName()+"手里的钱:"+nowMoney);
        }
    }
}
同步代码块
复制代码

 

4、JUC

测试JUC安全类型的集合CopyOnWriteArrayList

它是java.util.concurrent包下的。

复制代码
import java.util.concurrent.CopyOnWriteArrayList;

public class TestJUC {
    public static void main(String[] args) {
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList();

        for (int i = 0; i < 1000; i++) {
            new Thread(()->{
                list.add(Thread.currentThread().getName());
            }).start();
        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }
}

执行结果:1000
View Code
复制代码

 

5、死锁

多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形,某一个同步块同时拥有“两个以上对象的锁”时,就可能会发生“死锁”问题。

理解:就是两个线程都拥有着对方想要的资源,对手中的资源还不愿意放手,形成僵持。

测试:出现死锁

复制代码
public class DeadLock {
    public static void main(String[] args) {
        HuaZhuang g1 = new HuaZhuang(0, "灰姑凉");
        HuaZhuang g2 = new HuaZhuang(1, "白雪公主");

        g1.start();
        g2.start();
    }
}

//口红
class KouHong{}

//镜子
class Mirror{}

class HuaZhuang extends Thread{
    //需要的资源,一份资源用static保证只有一份
    static Mirror mirror = new Mirror();
    static KouHong kouHong = new KouHong();

    int choice;//选择
    String girlName;//使用化妆品的人

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

    @Override
    public void run() {
        try {
            huazhuang();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    //化妆,互相持有对方的锁,就是需要拿到对方的资源
    private void huazhuang() throws InterruptedException{
        if (choice == 0) {
            //获得口红的锁
            synchronized (kouHong){
                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 (kouHong) {
                    System.out.println(this.girlName + "获得口红的锁");
                }
            }
        }
    }
}

测试结果:
灰姑凉获得口红的锁
白雪公主获得镜子的锁
死锁案例
复制代码

 

解决办法:

复制代码
private void huazhuang() throws InterruptedException{
    if (choice == 0) {
        //获得口红的锁
        synchronized (kouHong){
            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);
        }
        //2秒钟后想获得口红
        synchronized (kouHong) {
            System.out.println(this.girlName + "获得口红的锁");
        }
    }
}

结果:
灰姑凉获得口红的锁
白雪公主获得镜子的锁
白雪公主获得口红的锁
灰姑凉获得镜子的锁
View Code
复制代码

 

产生死锁四个必要条件:

  1. 互斥条件,一个资源每次只能被一个进程使用

  2. 请求与保持条件,一个进程因请求资源而阻塞时,对已获得的资源保持不放

  3. 不剥夺条件,进程已获得的进程,在未使用完之前,不能前行剥夺

  4. 循环等待条件,若干个进程之间形成一种头尾相接的循环等待资源关系

ps:以上的四个条件,我们只要破除其中一个或者多个条件就可以避免死锁的发生。

6、Lock锁

显示定义同步锁对象来实现同步,同步锁使用Lock对象充当。

Lock接口是控制多个线程对共享资源进行访问的工具,提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象

ReentranLock可重入锁)类实现了Lock,他拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentranLock,可以显示加锁,释放锁。

使用方法:

复制代码
class A{
 private final ReentrantLock lock = new ReentrantLock();
 try {
                lock.lock();//加锁
                }finally {
                lock.unlock();//解锁
            }
}
View Code
复制代码

测试:

复制代码
public class TestLock {
    public static void main(String[] args) {
        TestLock2 testLock2 = new TestLock2();

        new Thread(testLock2).start();
        new Thread(testLock2).start();
        new Thread(testLock2).start();
    }
}

class TestLock2 implements Runnable{
    int ticket = 10;

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

    @Override
    public void run() {
        while (true){

            try {
                lock.lock();//加锁
                if (ticket >0){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(ticket--);
                }else {
                    break;
                }
            }finally {
                lock.unlock();//解锁
            }

        }
    }
}
Lock案例
复制代码

synchronized和lock的对比

  • lock是显示锁(手动开启和关闭,别忘记关闭锁), synchronized是隐式锁,除了作用域会自动释放

  • lock只是代码块锁, synchronized有代码块锁和方法锁

  • 使用lock锁,JVM会使用较少的时间来调度线程,性能更好。并且具有更好的扩展性(提供更多的子类)

  • 优先使用顺序:

    • Lock->同步代码块(已经进入方法,分配了相应资源)->同步方法(在方法体之外)

五、线程协作

生产者消费者问题

生产者 --> 数据缓存区 --> 消费者

这是线程同步问题,生产者和消费者共享一个资源,并且生活者和消费者之间相互依赖,互为条件。

  • 对生产者在没有生产产品之前,要告知消费者等待,而生产了产品之后,又需要马上通知消费者消费

  • 对消费者,在消费之后,要通知生产者已经结束消费,需要生产心得产品以供消费

所以在生产者消费者问题中,仅有synchronized是不够的

  • synchronized可阻止并发更新同一个共享数据,实现同步

  • synchronized不能用来实现不同线程之间的消息传递(通信)

1、线程通信

Java提供了一下几个方法解决线程之间的通信问题:

  • wait():表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁

  • wait(long timeout):指定等待的毫秒数

  • notify():唤醒一个处于等待状态的线程

  • notifyAll():唤醒同一个对象所有调用wait()方法的线程,优先级别搞的线程优先调度

ps:都是Object方法,都只能在同步方法或者同步代码块中使用,否在会抛出异常

2、解决方式1--管程法

并发协作模型“生产者/消费者模式” --管程法

生产者 --> 数据缓存区 --> 消费者

生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据

复制代码
// 生产者 ,消费者, 产品, 缓冲区
public class TestPC {
    public static void main(String[] args) {
        SynContainer synContainer = new SynContainer();

        new Productor(synContainer).start();
        new Consumer(synContainer).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++) {
            System.out.println("生产了"+i+"只东西");
            container.push(new Things(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("消费了"+i+"只鸡");
        }
    }
}
//产品
class Things{
    int id; //产品编号

    public Things(int id) {
        this.id = id;
    }
}
//缓冲区
class SynContainer {
    //容器大小
    Things[] things = new Things[10];
    //容器计数器
    int conut = 0;

    //生产者放入产品
    public synchronized void push(Things thing){
        //如果容器满了,就需要等待消费者
        if (conut == things.length) {
            //通知消费者消费,生产等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果容器没满了,就需要丢入商品
        things[conut] = thing;
        conut++;

        //通知消费者消费
        this.notifyAll();
    }

    //消费者消费产品
    public synchronized Things pop(){
        //判断是否消费
        if (conut == 0) {
            //等待生产者生产,消费者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //如果可以消费,就消费
        conut--;
        Things thing = things[conut];

        //使用完了,通知生产者生产
        this.notifyAll();
        return thing;
    }
}
管程法
复制代码

3、解决方式2--信号灯法

并发协作模型“生产者/消费者模式” --信号灯法

复制代码
//通过标志位
public class Test{
    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;
    }
}
信号灯法案例
复制代码

六、线程池

好处:

  1. 提高了相应速度(减少了创建新线程的时间)

  2. 降低资源消耗(重复利用线程池中线程,不需要每次创建)

  3. 便于线程管理

    • corePoolSize:核心池的大小

    • maxmunPoolSize:最大线程数

    • minAliveTime:线程没有任务最多保持多长时间后会终止

ExecutorService:线程接口

  • void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable

  • <T>Future<T> submit(Callable<T> task):执行任务,有返回值,一般又来执行Callable

  • void shutdown():关闭连接池

Executors:工具类,线程池的工厂类,用于创建并返回不同类型的线程池

复制代码
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestPool {
    public static void main(String[] args) {
        //创建线程池
        ExecutorService service = Executors.newFixedThreadPool(10);

        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());

    }
}
线程池
复制代码

 

 

 

 

posted @   暮商  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示