1.线程简介
1.1 进程和线程
- 说起进程,就不得不说下程序。程序是指令和数据的有序集合,其本身没有任何运行的含义,是一个静态的概念。
- 而进程则是执行程序的一次执行过程,他是一个动态的概念。是系统资源分配的单位
- 通常在一个进程中可以包含若干个线程,当然一个进程至少有一个线程,不然没有存在的意义。线程是CPU调度和执行的单位
注意:很多多线程是模拟出来的,真正的多线程是指有多个cpu,即多核,如服务器。如果是模拟出来的多线程,即在一个cpu的情况下,cpu只能执行一个代码,因为切换的很快,所以就有同时执行的错觉。
1.2 核心概念
- 线程就是独立的执行路径
- 在程序运行时,即使没有自己创建线程,后台也会有多个线程,如主线程,gc线程
- main()称之为主线程,为系统的入口,用于执行整个程序
- 在一个进程中,如果开辟了多个线程,线程的运行由调度器安排调度,调度器是与操作系统紧密相关的,先后顺序是不能人为的干预的
- 对同一份资源操作时,会存在资源抢夺的问题,需要加入并发控制
- 线程会带来额外的开销,如cpu调度时间,并发控制开销
- 每个线程在自己的工作内存交互,内存控制不当会造成数据不一致
2.线程实现
2.1 实现多线程的三种方式
继承Thread类 , 实现Runnable接口, 实现Callable接口
2.2 继承Thread类
实现步骤:
- 自定义线程类继承Thread类
- 重写run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程
package com.lesson.demo01;public class TestThread1 extends Thread{ @Override public void run() { //run方法线程体 for (int i = 0; i < 200; i++) { System.out.println("我在看代码--"+i); } } public static void main(String[] args) { //main线程是主线程 TestThread1 testThread1 = new TestThread1(); //调用start方法开启线程 testThread1.start(); for (int i = 0; i < 1000; i++) { System.out.println("我在学习多线程--"+i); } }}
执行结果:
我们发现主线程和子线程是并发交替执行的。
总结:线程开启不一定立即执行,由cpu调度执行。
2.3 练习:实现多线程同步下载图片
package com.lesson.demo01;import org.apache.commons.io.FileUtils;import java.io.File;import java.io.IOException;import java.net.URL;public class TestThread2 extends Thread { private String url; private String fileName; public TestThread2(String url, String fileName) { this.url = url; this.fileName = fileName; } @Override public void run() { new WebDownloader().downloader(url,fileName); System.out.println("下载了文件名为:"+fileName); } public static void main(String[] args) { TestThread2 t1 = new TestThread2("https://gimg2.baidu.com/image_search/src=http://1812.img.pp.sohu.com.cn/images/blog/2009/11/18/18/8/125b6560a6ag214.jpg&refer=http://1812.img.pp.sohu.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625039900&t=6bc9b0d4ea6e6aa8f584a5ebe922442a", "1.jpg"); TestThread2 t2 = new TestThread2("https://gimg2.baidu.com/image_search/src=http://youimg1.c-ctrip.com/target/tg/035/063/726/3ea4031f045945e1843ae5156749d64c.jpg&refer=http://youimg1.c-ctrip.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625039900&t=99a6ee2704829aab2262a6f21faf35fb", "2.jpg"); TestThread2 t3 = new TestThread2("https://gimg2.baidu.com/image_search/src=http://2c.zol-img.com.cn/product/124_500x2000/748/ceZOdKgDAFsq2.jpg&refer=http://2c.zol-img.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625039900&t=d1739a242ca207055945a00589c1b025", "3.jpg"); t1.start(); t2.start(); t3.start(); }}class WebDownloader{ public void downloader(String url,String fileName){ try { FileUtils.copyURLToFile(new URL(url),new File(fileName)); } catch (IOException e) { e.printStackTrace(); } }}
2.4 实现Runnable接口
实现步骤:
- 定义MyRunnable类实现Runnable接口
- 实现run()方法,编写线程执行体
- 创建线程对象,调用start()方法后启动线程
package com.lesson.demo01;
public class TestRunnable1 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("我在看代码--"+i);
}
}
public static void main(String[] args) {
TestRunnable1 testRunnable1 = new TestRunnable1();
//创建线程对象,通过线程对象来开启我们的线程。
new Thread(testRunnable1).start();
for (int i = 0; i < 1000; i++) {
System.out.println("我在学习多线程--"+i);
}
}
}
执行结果
小结:
继承Thread类
- 子类继承Thread类具备多线程能力
- 启动线程:子类对象.start()
- 不建议使用:避免OOP单继承局限性
实现Runnable接口
- 实现接口Runnable具有多线程能力
- 启动线程:传入目标对象+Thread对象.start()
- 推荐使用:避免单继承局限性,灵活多变,方便同一个对象被多个线程使用
2.5 初始并发问题
我们通过买票需求来发现问题
package com.lesson.demo01;
//多个线程同时操作一个对象//买火车票的例子
public class TestRunnable2 implements Runnable {
private int ticketNums = 10;
@Override
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) {
TestRunnable2 testRunnable = new TestRunnable2();
new Thread(testRunnable,"小明").start();
new Thread(testRunnable,"小张").start();
new Thread(testRunnable,"黄牛党").start();
}
}
执行结果
我们发现问题,多个线程操作同一个资源的情况下,线程不安全,数据紊乱。
2.6 实现Callable接口
实现步骤
- 实现Callable接口,需要返回值类型
- 重写call方法,需要抛出异常
- 创建目标对象
- 创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1);
- 提交执行:Future result1 = ser.submit(t1);
- 获取结果:boolean r1 = result1.get();
- 关闭服务: ser.shutdownNow();
package com.lesson.demo01;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TestCallable implements Callable<Boolean> {
private String url;
private String fileName;
public TestCallable(String url, String fileName) {
this.url = url;
this.fileName = fileName;
}
@Override
public Boolean call() throws Exception {
new WebDownloader2().downloader(url,fileName);
System.out.println("下载了文件名为:"+fileName);
return true;
}
public static void main(String[] args) throws Exception{
TestCallable call1 = new TestCallable("https://gimg2.baidu.com/image_search/src=http://1812.img.pp.sohu.com.cn/images/blog/2009/11/18/18/8/125b6560a6ag214.jpg&refer=http://1812.img.pp.sohu.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625039900&t=6bc9b0d4ea6e6aa8f584a5ebe922442a", "1.jpg");
TestCallable call2 = new TestCallable("https://gimg2.baidu.com/image_search/src=http://youimg1.c-ctrip.com/target/tg/035/063/726/3ea4031f045945e1843ae5156749d64c.jpg&refer=http://youimg1.c-ctrip.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625039900&t=99a6ee2704829aab2262a6f21faf35fb", "2.jpg");
TestCallable call3 = new TestCallable("https://gimg2.baidu.com/image_search/src=http://2c.zol-img.com.cn/product/124_500x2000/748/ceZOdKgDAFsq2.jpg&refer=http://2c.zol-img.com.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1625039900&t=d1739a242ca207055945a00589c1b025", "3.jpg");
//创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> s1 = ser.submit(call1);
Future<Boolean> s2 = ser.submit(call2);
Future<Boolean> s3 = ser.submit(call3);
//获取结果
Boolean r1 = s1.get();
Boolean r2 = s2.get();
Boolean r3 = s3.get();
//关闭服务
ser.shutdownNow();
}
}
class WebDownloader2{
public void downloader(String url,String fileName){
try {
FileUtils.copyURLToFile(new URL(url),new File(fileName));
} catch (IOException e) {
e.printStackTrace();
}
}
}
好处:
- 可以定义返回值
- 可以抛出异常
3.线程状态
线程方法
方法 | 说明 |
setPriority(int newPriority) | 更改线程的优先级 |
static void sleep(long mills) | 在指定的毫秒数内让当前正在执行的线程休眠 |
void join() | 等待该线程终止 |
static void yield() | 暂停当前正在执行的线程对象,并执行其他线程 |
void interrupt() | 中断线程,别用这个方式 |
boolean isAlive() | 测试线程是否处于活动状态 |
线程停止
- 建议线程正常停止 -----> 利用次数,不建议死循环
- 建议使用标志位------->设置一个标志位
- 不要使用stop或者destroy等过时或者JDK不建议使用的方法
package com.lesson.demo03;
public class TestStop implements Runnable {
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("run-------"+i++);
}
}
private void stop(){
this.flag = false;
}
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 500; i++) {
System.out.println("main---"+i);
if(i==400){
testStop.stop();
System.out.println("线程该停止了");
}
}
}
}
执行结果:
线程休眠
- sleep(时间)指定当前线程阻塞的毫秒数 (1000ms = 1s)
- sleep存在异常InterruptedException
- sleep时间达到后线程进入就绪状态
- sleep可以模拟网络延时,倒计时等
- 每一个对象都有一个锁,sleep不会释放锁
package com.lesson.demo03;
//模拟倒计时
public class TestSleep2{
public static void main(String[] args) {
try {
tenDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void tenDown() throws InterruptedException {
int num = 10;
while(true){
Thread.sleep(1000);
System.out.println(num--);
if(num<=0){
break;
}
}
}
}
线程礼让
- 礼让线程,让当前正在执行的线程暂停,但不阻塞
- 将线程从运行状态转为运行状态
- 让cpu重新调度,礼让不一定成功,看cpu心情。
package com.lesson.demo03;
//礼让不一定成功
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合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞。
package com.lesson.demo03;
//测试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) throws InterruptedException {
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
for (int i = 0; i < 200; i++) {
if(i == 100){
thread.join();
}
System.out.println("主线程:----"+i);
}
}
}
观察线程状态 Thread.State
- NEW 尚未启动的线程处于此状态
- RUNNABLE 在Java虚拟机中执行的线程处于此状态
- BLOCKED 被阻塞等待监视器锁定的线程处于此状态
- WAITING 正在等待另一个线程执行特定动作的线程处于此状态
- TIMED_WAITING 正在等待另一个线程执行动作达到指定等待时间的线程处于此状态
- TERMINATED 已退出的线程处于此状态
package com.lesson.demo03;
public class TestState {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
for (int i = 0; i < 10; 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);
}
}
}
线程的优先级
- Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行
- 线程的优先级用数字表示,范围从1-10
- Thread.MIN_PRIORITY = 1;
- Thread.MAX_PRIORITY = 10;
- Thread.NORM_PRIORITY = 5;
- 使用以下方式改变或获取优先级 getPriority() setPriority(int xxx)
package com.lesson.demo03;
public class TestPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"---->"+Thread.currentThread().getPriority());
}
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()+"优先级---->"+Thread.currentThread().getPriority());
TestPriority testPriority = new TestPriority();
Thread t1 = new Thread(testPriority);
Thread t2 = new Thread(testPriority);
Thread t3 = new Thread(testPriority);
Thread t4 = new Thread(testPriority);
Thread t5 = new Thread(testPriority);
Thread t6 = new Thread(testPriority);
t1.start();
t2.setPriority(Thread.MIN_PRIORITY);
t2.start();
t3.setPriority(Thread.NORM_PRIORITY);
t3.start();
t4.setPriority(7);
t4.start();
t5.setPriority(Thread.MAX_PRIORITY);
t5.start();
t6.setPriority(4);
t6.start();
}
}
守护线程
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕
- 虚拟机不用等待守护线程执行完毕
- 如:后台记录操作日志,监控内存,垃圾回收等
package com.lesson.demo03;
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); //默认是false, 正常线程都是用户线程
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 World=======");
}
}
4.线程同步
并发
同一个对象被多个线程同时操作。
处理多线程问题时,多个线程访问同一个对象,并且某些线程还想修改这个对象,这时候我们就需要线程同步,线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程在使用。
由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制 synchronized ,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可。存在以下问题:
- 一个线程持有锁会导致其他所有需要此锁的线程挂起
- 在多线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题
- 如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置,引起性能问题。
同步方法
由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包括两种用法:synchronized方法和synchronized块。
synchronized方法控制对 "对象" 的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行。
缺陷:若将一个大的方法申明为synchronized将会影响效率。
同步块
同步块:synchronized(Obj){ }
Obj称之为同步监视器
- Obj 可以是任何对象,但是推荐使用共享资源作为同步监视器
- 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者是class
同步监视器的执行过程
- 第一个线程访问,锁定同步监视器,执行其中代码
- 第二个线程访问,发现同步监视器被锁定,无法访问
- 第一个线程访问完毕,解锁同步监视器
- 第二个线程访问,发现同步监视器没有锁,然后锁定并访问
package com.lesson.demo04;
//通过synchronized 方法来解决 购票问题
public class TestSynchronized1 implements Runnable{
private int ticketNums = 10;
private boolean flag = true;
@Override
public void run() {
while(flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private synchronized void buy() throws InterruptedException {
if(ticketNums <= 0 ){
flag = false;
System.out.println("票不够了");
return ;
}
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+"获得了第"+ticketNums--+"票");
}
public static void main(String[] args) {
TestSynchronized1 test = new TestSynchronized1();
new Thread(test,"小明").start();
new Thread(test,"小黄").start();
new Thread(test,"小黑").start();
}
}
package com.lesson.demo04;
//通过synchronized块来解决取钱问题
public class TestSynchronized2 {
public static void main(String[] args) {
Amount amount = new Amount(100,"123");
Drawing you = new Drawing(amount,50,"my");
Drawing girl = new Drawing(amount,100,"girl");
you.start();
girl.start();
}
}
class Amount{
int money;
String no;
public Amount(int money, String no) {
this.money = money;
this.no = no;
}
}
class Drawing extends Thread{
Amount amount;
int drawingMoney;
public Drawing(Amount amount,int drawingMoney,String name){
super(name);
this.amount = amount;
this.drawingMoney = drawingMoney;
}
@Override
public void run() {
synchronized (amount){
if(amount.money-drawingMoney<0){
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
return ;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
amount.money = amount.money - drawingMoney;
System.out.println(amount.no+"余额为:"+amount.money);
}
}
}
死锁
多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形,某一个同步块同时拥有 "两个以上对象的锁" 时,就可能发生死锁问题。
产生死锁的四个必要条件
- 互斥条件:一个资源每次只能被一个进程使用
- 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放
- 不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺
- 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
死锁避免方法
只要想办法破其中的任意一个或多个条件就可以避免死锁发生。
Lock锁
- 从JDK 5.0开始,Java提供了更强大的线程同步机制-----通过显示定义同步锁对象来实现同步。同步锁使用Lock对象充当
- java.util.concurrent.locks.Lock接口是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象
- ReentrantLock(可重入锁)类实现了Lock,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显示加锁,释放锁。
package com.lesson.demo05;
import java.util.concurrent.locks.ReentrantLock;
public class TestLock implements Runnable {
private int ticketNums = 10;
private final ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) {
TestLock testLock = new TestLock();
new Thread(testLock).start();
new Thread(testLock).start();
new Thread(testLock).start();
}
@Override
public void run() {
while (true){
try {
lock.lock();//加锁
if(ticketNums <= 0){
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
} finally {
lock.unlock();//释放锁
}
}
}
}
synchronized 与 Lock的对比
- Lock是显式锁(手动开启和关闭锁,别忘记关闭锁)synchronized 是隐式锁,出了作用域自动释放
- Lock只有代码块锁,synchronized有代码块锁和方法锁
- 使用Lock锁,JVM将花费较少的时间来调度线程,性能更好。并且具有更好的扩展性(提供更多的子类)
- 优先使用顺序: Lock > 同步代码块 > 同步方法
5.线程通信
应用场景:
- 假设仓库中只能存放一件产品,生产者将生产出来的产品放入仓库,消费者将仓库中产品取走消费
- 如果仓库中没有产品,则生产者将产品放入仓库,否则停止生产并等待,直到仓库中的产品被消费者取走为止
- 如果仓库中放有产品,则消费者可以将产品取走消费,否则停止消费并等待,直到仓库中再次放入产品为止
分析:
这是一个线程同步问题,生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件。
- 对于生产者,没有生产产品之前,要通知消费者等待,而生产了产品之后,又需要马上通知消费者消费
- 对于消费者,在消费之后,要通知生产者已经结束消费,需要生产新的产品以供消费
- 再生产者消费者问题中,仅有synchronized是不够的,synchronized 可阻止并发更新同一个共享资源,实现了同步,synchronized 不能用来实现不同线程之间的消息传递(通信)
Java提供了几个方法解决线程之间的通信问题
方法名 | 作用 |
wait() | 表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁 |
wait(long timeout) | 指定等待的毫秒数 |
notify() | 唤醒一个处于等待状态的线程 |
notifyAll() | 唤醒同一个对象上所有调用wait()方法的线程,优先级别高的线程优先调度 |
注意:均是Object类的方法,都只能在同步方法或者同步代码块中使用,否则会抛出异常。
解决方式一:
并发写作模型 "生产者/消费者模式" --->管程法
- 生产者:负责生产数据的模块(可能是方法,对象,进程,线程);
- 消费者:负责处理数据的模块(可能是方法,对象,进程,线程);
- 缓冲区:消费者不能直接使用生产者的数据,他们之间有个 "缓冲区"
生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据
package com.lesson.demo06;
//管程法
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 synContainer;
public Productor(SynContainer synContainer){
this.synContainer = synContainer;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
synContainer.push(new Chicken(i));
System.out.println("生产了"+i+"只鸡");
}
}
}
//消费者
class Consumer extends Thread{
SynContainer synContainer;
public Consumer(SynContainer synContainer){
this.synContainer = synContainer;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println("消费了第"+ synContainer.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();
}
}else{
//如果没有满,我们就需要把产品丢入到容器中
chickens[count] = chicken;
count++ ;
this.notifyAll();
}
}
//取出
public synchronized Chicken pop(){
Chicken chicken=null;
//如果容器内的数量为0,则消费者等待,
if(count == 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
count--;
chicken = chickens[count];
//消费完,通知生产者生产
this.notifyAll();
}
return chicken;
}
}
解决方式二:
并发协作模型 "生产者/消费者模式" --->信号灯法
package com.lesson.demo06;
//信号灯法
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++) {
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++) {
this.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();
}
}
this.voice = voice;
this.flag = !this.flag;
System.out.println("演员演了:"+voice+"节目");
this.notifyAll();//通知消费者消费
}
public synchronized void watch(){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观众观看了:"+voice+"节目");
this.notifyAll();
this.flag = !this.flag;
}
}
6.线程池
背景
经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。
思路
提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。类似生活中的公共交通工具
好处
- 提高响应速度(减少了创建新线程的时间)
- 降低资源消耗(重复利用线程池中线程,不需要每次都创建)
- 便于线程管理
- corePoolSize: 核心池的大小
- maximumPoolSize: 最大线程数
- keepAliveTime: 线程没有任务时最多保持多长时间后会终止
JDK5.0起提供了线程池相关API:ExecutorService 和 Executors
ExecutorService:
真正的线程池接口。常见子类 ThreadPoolExecutor
- void execute(Runnable command); 执行任务/命令,没有返回值,一般用来执行Runnable
- Future submit(Callable task): 执行任务,有返回值,一般用来执行Callable
- void shutdown() : 关闭连接池
Executors :
工具类、线程池的工厂类,用于创建并返回不同类型的线程池
package com.lesson.demo06;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestPool {
public static void main(String[] args) {
//1:创建一个池子
ExecutorService service = Executors.newFixedThreadPool(10);
//2:执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//3:关闭链接
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}