1.线程状态概述
2.等待唤醒案例分析
3.等待唤醒案例代码实现
- 等待唤醒案例:线程之间的通信
- 创建一个顾客线程(消费者):告知老板要的包子的种类和数量,调用wait()方法,放弃CPU的执行,进入到WAITING状态(无限等待)
- 创建一个老板线程(生产者):花了5s做包子,做好后,调用notify()方法,唤醒顾客吃包子。
- 注意:
顾客和老板线程必须全部使用同步代码块包裹起来,保证等待和唤醒只能有一个在执行。
同步使用的锁对象必须保证唯一。
只有锁对象才能调用wait和notify方法。
- Object类中的方法:
- void wait()
在其它线程调用此对象的notify()方法或notifyAll()方法前,导致当前线程等待。
2. void notify()
唤醒在此对象监视器上等待的单个线程。
会继续执行wait方法之后的代码。
package zh.codegym.test.ExceptionAndThread.Demo10.WaitAndNotify;
public class Demo01WaitAndNotify {
public static void main(String[] args) {
// 创建锁对象,保证唯一
Object obj = new Object();
// 创建一个顾客线程(消费者)
new Thread(){
@Override
public void run() {
// 保证等待和唤醒只能有一个在执行,需要使用同步技术。
synchronized (obj){
System.out.println("告知包子的需求,种类和数量");
// 调用wait()方法,放弃CPU的执行,进入到WAITING状态(无限等待)
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 唤醒之后执行的代码
System.out.println("开吃");
}
}
}.start();
// 创建一个老板线程(生产者)
new Thread(){
@Override
public void run() {
// 花了5s做包子
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 保证等待和唤醒的线程只能有一个执行,需要使用同步技术。
synchronized (obj){
System.out.println("5秒之后,老板做好了包子,告知顾客,可以开吃了");
obj.notify();
}
}
}.start();
}
}
3.Object类中wait带参方法和notify
4.线程间通信
5.等待唤醒机制概述
6.等待唤醒机制需求分析
7.线程池的概念和原理
-
线程池作用:一个容纳多个线程的容器,用来存储线程,因为线程只执行一次就销毁,浪费资源。把线程存起来,使得线程可重复使用。
- 线程池三个好处:
降低资源消耗。减少了创建和销毁线程的次数,每个工作线程都可以被重复利用,可执行多个任务。
提高响应速度。当任务到达时,任务可以不需要的等到线程创建就能立即执行。
提高线程的可管理性。可以根据系统的承受能力,调整线程池中工作线程的数目,防止因为消耗过多的内存,服务器死机。
- 线程池:JDK1.5之后提供的
- java.util.concurrent.Executors:线程池的工厂类,用来生成线程池。
- Executors类中的静态方法:
static ExecutorService newFixedThreadPool(int nThreads)创建一个可重用固定线程数的线程池
参数:
in nThreads:创建线程池中包含的线程数量。
返回值:
ExecutorService接口,返回的是ExecutorService接口的实现类对象,我们可以使用ExecutorServic接
口接收(面向接口编程)
java.util.concurrent.ExecutorService:线程池接口
用来从线程池中获取线程,调用start方法,执行线程任务。
submit(Runnable task)提交一个Runnable任务用于执行。
关闭/销毁线程池的方法
void shutdown()
线程池的使用步骤:
1.使用线程池的工厂类Executors里边提供的静态方法newFixedThreadPool生产一个指定线程数量的线程池。
2.创建一个类,实现Runnable接口,重写run方法,设置线程任务。
3.调用ExecutorService中的方法submit,传递线程任务(实现类),开启线程,执行run方法。
4.调用ExecutorService中的方法shutdown销毁线程池(不建议执行)
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
public class Demo01ThreadPool{
public static void main(String[] args){
//1.使用线程池的工厂类Executors里边提供的静态方法newFixedThreadPool生产一个指定线程数量的线程池。
ExecutorService es = Executors.newFixedThreadPool(2);
//调用ExecutorService中的方法submit,传递线程任务(实现类),开启线程,执行run方法。
es.submit(new RunnableImpl());
//线程池会一直开启,使用完了线程,会自动把线程归还给线程池,线程可以继续使用。
es.submit(new RunnableImpl());//创建了一个新的线程执行
es.submit(new RunnableImpl());//创建了一个新的线程执行
//调用ExecutorService中的方法shutdown销毁线程池(不建议执行)
es.shutdown();
es.submit(new RunnableImpl());//抛异常,线程池都没有了,就不能获取线程了
}
}
/*
2.创建一个类,实现Runnable接口,重写run方法,设置线程任务
*/
public class RunnableImpl implements Runnable{
public void run(){
System.out.println(Thread.currentThread().getName());
}
}