多线程学习4:线程协作与线程池

线程协作

消费者生产者问题

生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件,线程之间需要通信。

方法名 作用
wait() 表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁
wait(long timeout) 指定等待的毫秒数
notify() 唤醒一个处于等待状态的线程
notifyAll() 唤醒同一个对象上所有调用wait()方法的线程,优先级别高的线程优先调用

都是Object类的方法,都只能在同步方法或者同步代码块中使用(synchronized),否则会抛出异常lllegalMonitorStateException

管程法

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

package com.company.testthread.thread;

//测试生产者消费者模型,利用缓冲区解决,管程法
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 Product(i));
            System.out.println("生产了"+i+"只鸡");
        }
        System.out.println("生产完成");
    }
}

//消费者
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+"鸡");
        }
        System.out.println("消费完成");
    }
}

//产品
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 chicken){
        //如果容器满了,等待消费者
        while (count==10){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //没有满,放入产品
        products[count]=chicken;
        count++;
        //可以通知消费者消费
        this.notifyAll();
    }

    //消费者拿取
    public synchronized Product pop(){
        //是否能拿取
        if(count==0){
            //等待生产
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        //可以消费
        count--;
        Product chicken = products[count];
        //通知生产者
        this.notifyAll();
        return chicken;
    }
}

信号灯法

判断一个标志位

package com.company.testthread.thread;

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){
            //为false,演员等待
            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){
            //为true,观众等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观众观看了:"+voice);
        //通知演员表演
        this.notifyAll();
        this.flag=!this.flag;
    }
}

线程池

  • 背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。

  • 思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。

  • 好处:

    • 提高响应速度(减少了创建新线程的时间)

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

    • 便于线程管理

      • corePoolSize:核心池的大小
      • maximumPoolSize:最大线程数
      • keepAliveTime:线程没有任务时最多保持多长时间后会终止

使用线程池

ExecutorService和Executors

ExecutorService:真正的线程池接口。常见的子类ThreadPoolExecutor。

  • void execute(Runnable commend):执行任务/命令,没有返回值,一般用来执行Runnable
  • Futuresubmit(Callable task):执行任务,有返回值,一般又来执行Callable
  • void shutdown():关闭连接池

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

使用Runnable

package com.company.testthread.thread;

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

public class TestPool {
    public static void main(String[] args) {
        //创建服务,创建线程池
//        newFixedThreadPool 参数为:线程池大小
        ExecutorService service = Executors.newFixedThreadPool(10);

        //执行
        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());
    }
}
posted @ 2022-09-21 12:03  饺子少蘸醋  阅读(20)  评论(0编辑  收藏  举报