Java多线程(三)、线程的通信、wait(),notify(),notifyAll()、生产者/消费者问题、创建线程的方式三:实现Callable接口、创建线程的方式四:使用线程池

简介: 提高响应速度(减少了创建新线程的时间)降低资源消耗(重复利用线程池中线程,不需要每次都创建)便于线程管理corePoolSize:核心池的大小maximumPoolSize:最大线程数 keepAliveTime:线程没有任务时最多保持多长时间后会终止call()可以有返回值的、call()可以抛出异常,被外面的操作捕获,获取异常的信息、Callable是支持泛型的wait():一旦执行此方法,当前线程就进入阻塞状态,并释放同步监视器。notify():一旦执行此方法,就会唤醒被wait的一个线程。如果有多

@[toc]

1.多线程

1.5线程的通信

1.5.1wait(),notify(),notifyAll()

wait():一旦执行此方法,当前线程就进入阻塞状态,并释放同步监视器。令当前线程挂起并放弃CPU、同步资源并等待,使别的线程可访问并修改共享资源,而当前线程排队等候其他线程调用notify()或notifyAll()方法唤醒,唤醒后等待重新获得对监视器的所有权后才能继续执行。

notify():一旦执行此方法,就会唤醒被wait的一个线程。如果有多个线程被wait,就唤醒优先级高的那个。

notifyAll():一旦执行此方法,就会唤醒所有被wait的线程。

说明:
1.wait(),notify(),notifyAll()三个方法必须使用在同步代码块或同步方法中。
2.wait(),notify(),notifyAll()三个方法的调用者必须是同步代码块或同步方法中的同步监视器。否则,会出现IllegalMonitorStateException异常
3.wait(),notify(),notifyAll()三个方法是定义在java.lang.Object类中。

1.5.1.1wait()方法

在当前线程中调用方法: 对象名.wait()
使当前线程进入等待(某对象)状态 ,直到另一线程对该对象发出 notify (或notifyAll) 为止。
调用方法的必要条件:当前线程必须具有对该对象的监控权(加锁)
调用此方法后,当前线程将释放对象监控权 ,然后进入等待
在当前线程被notify后,要重新获得监控权,然后从断点处继续代码的执行。

1.5.1.2notify()/notifyAll()

在当前线程中调用方法: 对象名.notify()
功能:唤醒等待该对象监控权的一个/所有线程。
调用方法的必要条件:当前线程必须具有对该对象的监控权(加锁)

1.5.2线程通信的例子:使用两个线程打印 1-100。线程1, 线程2 交替打印

package com.my.java2;
/**
 * @author Redamancy
 * @create 2022-08-08 10:07
 */
class Number implements Runnable{

    private int number = 1;
    private Object obj = new Object();

    @Override
    public void run() {
        while (true){
            synchronized(obj){
                //:一旦执行此方法,就会唤醒被wait的一个线程。如果有多个线程被wait,就唤醒优先级高的那个。
                obj.notify();
                if(number <= 100){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ":" + number);
                    number++;
                    try {
                        //一旦执行此方法,当前线程就进入阻塞状态,并释放同步监视器。
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else{
                    break;
                }
            }
        }
    }
}
public class CommunicationTest {
    public static void main(String[] args) {
        Number number = new Number();
        Thread t1 = new Thread(number);
        Thread t2 = new Thread(number);

        t1.setName("线程1");
        t2.setName("线程2");

        t1.start();
        t2.start();
    }

}

在这里插入图片描述

线程1:1
线程2:2
线程1:3
线程2:4
线程1:5
线程2:6
线程1:7
线程2:8
线程1:9
线程2:10
线程1:11
线程2:12
线程1:13
线程2:14
线程1:15
线程2:16
线程1:17
线程2:18
线程1:19
线程2:20
线程1:21
线程2:22
线程1:23
线程2:24
线程1:25
线程2:26
线程1:27
线程2:28
线程1:29
线程2:30
线程1:31
线程2:32
线程1:33
线程2:34
线程1:35
线程2:36
线程1:37
线程2:38
线程1:39
线程2:40
线程1:41
线程2:42
线程1:43
线程2:44
线程1:45
线程2:46
线程1:47
线程2:48
线程1:49
线程2:50
线程1:51
线程2:52
线程1:53
线程2:54
线程1:55
线程2:56
线程1:57
线程2:58
线程1:59
线程2:60
线程1:61
线程2:62
线程1:63
线程2:64
线程1:65
线程2:66
线程1:67
线程2:68
线程1:69
线程2:70
线程1:71
线程2:72
线程1:73
线程2:74
线程1:75
线程2:76
线程1:77
线程2:78
线程1:79
线程2:80
线程1:81
线程2:82
线程1:83
线程2:84
线程1:85
线程2:86
线程1:87
线程2:88
线程1:89
线程2:90
线程1:91
线程2:92
线程1:93
线程2:94
线程1:95
线程2:96
线程1:97
线程2:98
线程1:99
线程2:100

Process finished with exit code 0

1.5.3经典例题:生产者/消费者问题

生产者(Productor)将产品交给店员(Clerk),而消费者(Customer)从店员处取走产品,店员一次只能持有固定数量的产品(比如:20),如果生产者试图生产更多的产品,店员会叫生产者停一下,如果店中有空位放产品了再通知生产者继续生产;如果店中没有产品了,店员会告诉消费者等一下,如果店中有产品了再通知消费者来取走产品。
这里可能出现两个问题:
生产者比消费者快时,消费者会漏掉一些数据没有取到。
消费者比生产者快时,消费者会取相同的数据

分析:

  1. 是否是多线程问题?是,生产者线程,消费者线程
  2. 是否有共享数据?是,店员(或产品)
  3. 如何解决线程的安全问题?同步机制,有三种方法
  4. 是否涉及线程的通信?是
package com.my.java2;

/**
 * @author Redamancy
 * @create 2022-08-08 11:12
 */

class Clerk{
    private int productCount = 0;

    //消费产品
    public synchronized void consumeProduct() {
        if(productCount > 0){
            System.out.println(Thread.currentThread().getName() + ":开始消费第" + productCount + "个产品");
            productCount--;
            notify();
        }else{
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
    //生产产品
    public synchronized void produceProduct() {
        if(productCount < 20){
            productCount++;
            System.out.println(Thread.currentThread().getName() + ":开始生产第" + productCount + "个产品");
            notify();
        }else{
            //等待
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class Producer extends Thread{//生产者
    private Clerk clerk;
    public Producer(Clerk clerk){
        this.clerk = clerk;
    }

    @Override
    public void run() {
        System.out.println(getName() + ":开始生产产品...");
        while (true){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.produceProduct();
        }
    }
}
class Consumer extends Thread{//消费者
    private Clerk clerk;
    public Consumer(Clerk clerk){
        this.clerk = clerk;
    }

    @Override
    public void run() {
        System.out.println(getName() + ":开始消费产品...");
        while (true){
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.consumeProduct();
        }
    }
}
public class ProductTest {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Producer p1 = new Producer(clerk);
        Consumer c1 = new Consumer(clerk);
        Consumer c2 = new Consumer(clerk);

        p1.setName("生产者1");
        c1.setName("消费者1");
        c2.setName("消费者2");

        p1.start();
        c1.start();
        c2.start();
    }
}

在这里插入图片描述

1.6JDK5.0新增线程创建方式

1.6.1新增方式一:创建线程的方式三:实现Callable接口。 --- JDK 5.0新增

与使用Runnable相比, Callable功能更强大些
相比run()方法,可以有返回值
方法可以抛出异常
支持泛型的返回值
需要借助FutureTask类,比如获取返回结果

Future接口
可以对具体Runnable、Callable任务的执行结果进行取消、查询是否完成、获取结果等。
FutrueTask是Futrue接口的唯一的实现类
FutureTask 同时实现了Runnable, Future接口。它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值

1.6.1.1例子

如何理解实现Callable接口的方式创建多线程比实现Runnable接口创建多线程方式强大?

  1. call()可以有返回值的。
  2. call()可以抛出异常,被外面的操作捕获,获取异常的信息

    1. Callable是支持泛型的
package com.my.java2;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author Redamancy
 * @create 2022-08-08 15:30
 */
//1.创建一个实现Callable的实现类
class NumThread implements Callable {
    //2.实现call方法,将此线程需要执行的操作声明在call()中
    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            if(i % 2 == 0){
                System.out.println(i);
                sum += i;
            }
        }
        return sum;
    }
}
public class ThreadNew {
    public static void main(String[] args) {
        //3.创建Callable接口实现类的对象
        NumThread numThread = new NumThread();
        //4.将此Callable接口实现类的对象作为传递到FutureTask构造器中,创建FutureTask的对象
        FutureTask futureTask = new FutureTask(numThread);
        //5.将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start()
        new Thread(futureTask).start();
        try {
            //6.获取Callable中call方法的返回值
            //get()返回值即为FutureTask构造器参数Callable实现类重写的call()的返回值。
            Object sum = futureTask.get();
            System.out.println("总合为:" + sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40
42
44
46
48
50
52
54
56
58
60
62
64
66
68
70
72
74
76
78
80
82
84
86
88
90
92
94
96
98
100
总合为:2550

Process finished with exit code 0

1.6.2新增方式二:创建线程的方式四:使用线程池

背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。
思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。类似生活中的公共交通工具。
好处:
提高响应速度(减少了创建新线程的时间)
降低资源消耗(重复利用线程池中线程,不需要每次都创建)
便于线程管理
corePoolSize:核心池的大小
maximumPoolSize:最大线程数
keepAliveTime:线程没有任务时最多保持多长时间后会终止
......

创建多线程有几种方式?四种!

1.6.2.1线程池相关API

JDK 5.0起提供了线程池相关API:ExecutorService 和 Executors
ExecutorService:真正的线程池接口。常见子类ThreadPoolExecutor
void execute(Runnable command) :执行任务/命令,没有返回值,一般用来执行Runnable
Future submit(Callable task):执行任务,有返回值,一般又来执行Callable
void shutdown() :关闭连接池
Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池
Executors.newCachedThreadPool():创建一个可根据需要创建新线程的线程池
Executors.newFixedThreadPool(n); 创建一个可重用固定线程数的线程池
Executors.newSingleThreadExecutor() :创建一个只有一个线程的线程池
Executors.newScheduledThreadPool(n):创建一个线程池,它可安排在给定延迟后运行命令或者定期地执行。

1.6.2.2例子

package com.my.java2;

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

/**
 * @author Redamancy
 * @create 2022-08-08 15:40
 */
class NumberThread implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            if(i % 2 == 0){
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}
class NumberThread1 implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            if (i % 2 != 0){
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}
public class ThreadPool {
    public static void main(String[] args) {
        //1. 提供指定线程数量的线程池
        ExecutorService service = Executors.newFixedThreadPool(10);
        ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
        //设置线程池的属性
//        System.out.println(service.getClass());
//        service1.setCorePoolSize(15);
//        service1.setKeepAliveTime();

        //2.执行指定的线程的操作。需要提供实现Runnable接口或Callable接口实现类的对象
        service.execute(new NumberThread());//适合适用于Runnable
        service.execute(new NumberThread1());//适合适用于Runnable
//        service.submit(Callable callable);
        //3.关闭连接池
        service.shutdown();
    }
}
pool-1-thread-1:0
pool-1-thread-1:2
pool-1-thread-1:4
pool-1-thread-1:6
pool-1-thread-1:8
pool-1-thread-1:10
pool-1-thread-1:12
pool-1-thread-1:14
pool-1-thread-1:16
pool-1-thread-1:18
pool-1-thread-1:20
pool-1-thread-1:22
pool-1-thread-1:24
pool-1-thread-1:26
pool-1-thread-1:28
pool-1-thread-1:30
pool-1-thread-1:32
pool-1-thread-1:34
pool-1-thread-1:36
pool-1-thread-1:38
pool-1-thread-2:1
pool-1-thread-1:40
pool-1-thread-2:3
pool-1-thread-1:42
pool-1-thread-2:5
pool-1-thread-1:44
pool-1-thread-2:7
pool-1-thread-2:9
pool-1-thread-2:11
pool-1-thread-2:13
pool-1-thread-2:15
pool-1-thread-1:46
pool-1-thread-2:17
pool-1-thread-2:19
pool-1-thread-2:21
pool-1-thread-1:48
pool-1-thread-2:23
pool-1-thread-1:50
pool-1-thread-2:25
pool-1-thread-1:52
pool-1-thread-2:27
pool-1-thread-1:54
pool-1-thread-2:29
pool-1-thread-1:56
pool-1-thread-2:31
pool-1-thread-1:58
pool-1-thread-2:33
pool-1-thread-2:35
pool-1-thread-2:37
pool-1-thread-2:39
pool-1-thread-2:41
pool-1-thread-2:43
pool-1-thread-2:45
pool-1-thread-2:47
pool-1-thread-2:49
pool-1-thread-1:60
pool-1-thread-2:51
pool-1-thread-1:62
pool-1-thread-2:53
pool-1-thread-1:64
pool-1-thread-2:55
pool-1-thread-1:66
pool-1-thread-2:57
pool-1-thread-2:59
pool-1-thread-2:61
pool-1-thread-1:68
pool-1-thread-2:63
pool-1-thread-2:65
pool-1-thread-2:67
pool-1-thread-2:69
pool-1-thread-2:71
pool-1-thread-2:73
pool-1-thread-2:75
pool-1-thread-2:77
pool-1-thread-2:79
pool-1-thread-2:81
pool-1-thread-2:83
pool-1-thread-2:85
pool-1-thread-2:87
pool-1-thread-2:89
pool-1-thread-2:91
pool-1-thread-2:93
pool-1-thread-2:95
pool-1-thread-2:97
pool-1-thread-2:99
pool-1-thread-1:70
pool-1-thread-1:72
pool-1-thread-1:74
pool-1-thread-1:76
pool-1-thread-1:78
pool-1-thread-1:80
pool-1-thread-1:82
pool-1-thread-1:84
pool-1-thread-1:86
pool-1-thread-1:88
pool-1-thread-1:90
pool-1-thread-1:92
pool-1-thread-1:94
pool-1-thread-1:96
pool-1-thread-1:98
pool-1-thread-1:100

想看完整版的多线程看我发的博客https://blog.csdn.net/Redamancy06/article/details/126229545?spm=1001.2014.3001.5502

目录
相关文章
|
7月前
|
Java 调度
Java中wait和notify详解
Java中wait和notify详解
58 0
Java中wait和notify详解
|
2天前
|
Java
Java一分钟:线程协作:wait(), notify(), notifyAll()
【5月更文挑战第11天】本文介绍了Java多线程编程中的`wait()`, `notify()`, `notifyAll()`方法,它们用于线程间通信和同步。这些方法在`synchronized`代码块中使用,控制线程执行和资源访问。文章讨论了常见问题,如死锁、未捕获异常、同步使用错误及通知错误,并提供了生产者-消费者模型的示例代码,强调理解并正确使用这些方法对实现线程协作的重要性。
16 3
|
9月前
|
Java 调度
【Java|多线程与高并发】wait和notify方法详解
在Java多线程环境中,线程之间是抢占式执行的,线程的调度是随机的.这就很难受了. 在很多情况下我们希望线程以我们想要的顺序来执行. 这就需要wait和notify这两个方法
|
10月前
|
Java 调度
Java中wait()方法和notify()/notifyAll()
Java中wait()方法和notify()/notifyAll()
|
安全 Java
Java并发编程之Wait和Notify
Java并发编程之Wait和Notify
114 0
Java并发编程之Wait和Notify
|
算法 Java 程序员
Java多线程之死锁问题,wait和notify
Java多线程之死锁问题,wait和notify
195 0
Java多线程之死锁问题,wait和notify
|
Java
Java多线程(5)--线程通信wait和notify
Java多线程(5)--线程通信wait和notify
103 0
|
监控 Java 数据挖掘
Java多线程(三)、线程的通信、wait(),notify(),notifyAll()、生产者/消费者问题、创建线程的方式三:实现Callable接口、创建线程的方式四:使用线程池
Java多线程(三)、线程的通信、wait(),notify(),notifyAll()、生产者/消费者问题、创建线程的方式三:实现Callable接口、创建线程的方式四:使用线程池
Java多线程(三)、线程的通信、wait(),notify(),notifyAll()、生产者/消费者问题、创建线程的方式三:实现Callable接口、创建线程的方式四:使用线程池
|
设计模式 监控 安全
Java多线程(完整版)、基本概念:程序、进程、线程、线程的创建和使用、线程的生命周期、线程的同步、线程的通信、JDK5.0新增线程创建方式、wait(),notify(),notifyAll()
Java多线程(完整版)、基本概念:程序、进程、线程、线程的创建和使用、线程的生命周期、线程的同步、线程的通信、JDK5.0新增线程创建方式、wait(),notify(),notifyAll()
Java多线程(完整版)、基本概念:程序、进程、线程、线程的创建和使用、线程的生命周期、线程的同步、线程的通信、JDK5.0新增线程创建方式、wait(),notify(),notifyAll()
|
设计模式 监控 安全
Java多线程(完整版)、基本概念:程序、进程、线程、线程的创建和使用、线程的生命周期、线程的同步、线程的通信、JDK5.0新增线程创建方式、wait(),notify(),notifyAll()
使用多线程的优点、Thread类、创建线程的两种方式继承Thread类、实现Runnable接口、Thread类的有关方法、线程的调度、无效的源发行版、线程的分类、Synchronized的使用方法、同步代码块、同步方法、同步机制中的锁、同步的范围、Lock(锁、不会释放锁的操作、单例设计模式之懒汉式(线程安全)、生产者/消费者问题、创建线程的方式三:实现Callable接口、创建线程的方式四:使用线程池、Lock是显式锁(手动开启和关闭锁,别忘记关闭锁),synchronized是隐式锁...
165 1
Java多线程(完整版)、基本概念:程序、进程、线程、线程的创建和使用、线程的生命周期、线程的同步、线程的通信、JDK5.0新增线程创建方式、wait(),notify(),notifyAll()