多线程
Thread 类定义的一些方法:
方法 | 含义 |
---|---|
getName() | 获取线程的名称 |
getPriority() | 获取线程的优先级 |
isAlive() | 确定线程是否仍然在运行 |
join() | 等待线程终止 |
run() | 线程的入口点 |
sleep() | 挂起线程一段时间 |
start() | 通过调用线程的 run() 方法启动线程 |
主线程:
- 其他子线程都是从主线程生成的
- 通常,主线程必须是最后结束执行的线程,因为它要执行各种关闭动作
1. 创建线程
- 扩展
Thread
类 - 实现
Runnable
接口
1.1 继承Thread类
package com.feiye.demo01;
// 创建线程方式一:继承 Thread 类,重写 run() 方法,调用 start 开启线程
public class TestThread1 extends Thread {
@Override
public void run() {
// run 方法线程体
for (int i = 0; i < 2000; i++) {
System.out.println("我在看代码——" + i);
}
}
public static void main(String[] args) {
// main 线程,主线程
// 创建一个线程对象
TestThread1 testThread1 = new TestThread1();
// 调用 start() 方法开启线程
testThread1.start();
for (int i = 0; i < 2000; i++) {
System.out.println("我在学习多线程——" + i);
}
}
}
网图下载
package com.feiye.demo01;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
// 练习 Thread,实现多线程同步下载图片
public class TestThread2 extends Thread {
private String url; // 网络图片地址
private String name; // 保存的文件名
public TestThread2(String url, String name) {
this.url = url;
this.name = name;
}
// 下载图片线程的执行体
@Override
public void run() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url, name);
System.out.println("下载了文件名为:" + name);
}
public static void main(String[] args) {
TestThread2 t1 = new TestThread2("https://c-ssl.duitang.com/uploads/item/202002/07/20200207133134_aubwp.jpg", "1.jpg");
TestThread2 t2 = new TestThread2("https://n.sinaimg.cn/sinacn10108/320/w2048h3072/20200302/8639-iqfqmat2644767.jpg", "2.jpg");
TestThread2 t3 = new TestThread2("https://c-ssl.duitang.com/uploads/item/202003/02/20200302102550_vwiiq.jpg", "3.jpg");
// 同时执行
t1.start();
t2.start();
t3.start();
}
}
// 下载器
class WebDownloader {
// 下载方法
public void downloader(String url, String name) {
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloader方法出现问题");
}
}
}
- 子类继承 Thread 类具备多线程能力
- 启动线程:子类对象.start()
- 不建议使用:避免OOP单继承局限性
1.2 实现 Runnable 接口
package com.feiye.demo01;
// 创建线程方式二:实现 runnable 接口,重写 run 方法,执行线程需要丢入 runnable 接口实现类,调用 start 方法
public class TestThread3 implements Runnable {
@Override
public void run() {
// run 方法线程体
for (int i = 0; i < 1000; i++) {
System.out.println("我在看代码——" + i);
}
}
public static void main(String[] args) {
// 创建 runnable 接口的实现类对象
TestThread3 testThread3 = new TestThread3();
// 创建线程对象,通过线程对象来开启我们的线程,代理
// Thread thread = new Thread(testThread3);
// thread.start();
new Thread(testThread3).start();
for (int i = 0; i < 1000; i++) {
System.out.println("我在学习多线程——" + i);
}
}
}
- 实现接口 Runnable 具有多线程能力
- 启动线程:传入目标对象 + Thread对象.start()
- 推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
对同一对象实现多线程
package com.feiye.demo01;
// 多个线程同时操作同一个对象
// 买火车票
// 发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱
public class TestThread4 implements Runnable {
// 票数
private int ticketNums = 10;
@Override
public void run() {
while(true) {
if (ticketNums <= 0) {
break;
}
System.out.println(Thread.currentThread().getName() + "--> 拿到了第" + ticketNums-- + "票");
}
}
public static void main(String[] args) {
TestThread4 ticket = new TestThread4();
new Thread(ticket, "小明").start();
new Thread(ticket, "老师").start();
new Thread(ticket, "黄牛").start();
}
}
龟兔赛跑
package com.feiye.demo01;
// 模拟龟兔赛跑
public class Race implements Runnable {
// 胜利者
private static String winner;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
// 模拟兔子休息
if ((Thread.currentThread().getName() == "兔子") && i%10 == 0) {
try {
Thread.sleep(20000);
} 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;
}
if (steps == 100) {
winner = Thread.currentThread().getName();
System.out.println("winner is " + 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 接口(了解即可)
- 实现 Callable 接口,需要返回值类型
- 重写 call 方法,需要抛出异常
- 创建目标对象
- 创建执行服务:
ExecutorService ser = Executors.newFixedThreadPool(1);
- 提交执行:
Future<Boolean> result1 = ser.submit(t1);
- 获取结果:
boolean r1 = result1.get()
- 关闭服务:
ser.shutdownNow();
package com.feiye.demo02;
import com.feiye.demo01.TestThread2;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
// 线程创建方式三:实现 callable 接口
/*
* 好处:
* 1. 可以定义返回值
* 2. 可以抛出异常
* */
public class TestCallable implements Callable {
private String url; // 网络图片地址
private String name; // 保存的文件名
public TestCallable(String url, String name) {
this.url = url;
this.name = name;
}
// 下载图片线程的执行体
@Override
public Boolean call() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url, name);
System.out.println("下载了文件名为:" + name);
return true;
}
public static void main(String[] args) {
TestCallable t1 = new TestCallable("https://c-ssl.duitang.com/uploads/item/202002/07/20200207133134_aubwp.jpg", "1.jpg");
TestCallable t2 = new TestCallable("https://n.sinaimg.cn/sinacn10108/320/w2048h3072/20200302/8639-iqfqmat2644767.jpg", "2.jpg");
TestCallable t3 = new TestCallable("https://c-ssl.duitang.com/uploads/item/202003/02/20200302102550_vwiiq.jpg", "3.jpg");
// 创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
// 提交执行
Future<Boolean> r1 = ser.submit(t1);
Future<Boolean> r2 = ser.submit(t2);
Future<Boolean> r3 = ser.submit(t3);
// 获取结果
try {
boolean rs1 = r1.get();
boolean rs2 = r2.get();
boolean rs3 = r3.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
// 关闭服务
ser.shutdownNow();
}
}
// 下载器
class WebDownloader {
// 下载方法
public void downloader(String url, String name) {
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloader方法出现问题");
}
}
}
2. 静态代理
package com.feiye.demo03;
// 静态代理模式:
/*
* 1. 真实对象和代理对象都要实现同一个接口
* 2. 代理对象要代理真实角色
*
* 好处:
* 1. 代理对象可以做很多真实对象做不了的事情
* 2. 真实对象专注做自己的事情
* */
public class StaticProxy {
public static void main(String[] args) {
You you = new You(); // 你要结婚
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("?");
}
}).start();
new WeddingCompany(new You()).HappyMarry();
// WeddingCompany weddingCompany = new WeddingCompany(you);
// weddingCompany.HappyMarry();
}
}
interface Marry {
void HappyMarry();
}
// 真实角色,你去结婚
class You implements Marry {
@Override
public void HappyMarry() {
System.out.println("。。。我不结婚");
}
}
// 代理角色,帮助你结婚(滚)
class WeddingCompany implements Marry {
// 代理谁 -> 真实目标角色
private Marry target;
public WeddingCompany(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. Lambda 表达式
- 避免匿名内部类定义过多
- 可以让代码看起来很简洁
- 去掉了一堆没有意义的代码,只留下核心的逻辑
- 其实质属于函数式编程的概念
(params) -> expression [表达式]
(params) -> statement [语句]
(params) -> { statements }
a-> System.out.println("i like lambda" + a)
new Thread (()->System.out.println("多线程学习。。。")).start();
函数式接口:
- 任何接口,如果只包含唯一一个抽象方法,那么就是一个函数式接口
public interface Runnable {
public abstract void run();
}
- 对于函数式接口,我们可以通过
lambda
表达式来创建该接口的对象
package com.feiye.lambda;
/*
* 推导lambda表达式
* */
public class TestLambda1 {
// 3. 静态内部类
static class Like2 implements ILike {
@Override
public void lambda() {
System.out.println("I like lambda2.");
}
}
public static void main(String[] args) {
ILike like = new Like();
like.lambda();
like = new Like2();
like.lambda();
// 4. 局部内部类
class Like3 implements ILike {
@Override
public void lambda() {
System.out.println("I like lambda3.");
}
}
like = new Like3();
like.lambda();
// 5. 匿名内部类,没有类的名称,必须借助接口或者父类
like = new ILike() {
@Override
public void lambda() {
System.out.println("I like lambda4.");
}
};
like.lambda();
// 6. 用 lambda 简化
like = ()->{
System.out.println("I like lambda5.");
};
like.lambda();
}
}
// 1. 定义一个函数式接口
interface ILike {
void lambda();
}
// 2. 实现类
class Like implements ILike {
@Override
public void lambda() {
System.out.println("I like lambda.");
}
}
package com.feiye.lambda;
public class TestLambda2 {
public static void main(String[] args) {
Ilove love = (int a)-> {
System.out.println("I love you->" + a);
};
love.love(2);
// 简化1:参数类型
love = (a)-> {
System.out.println("I love you->" + a);
};
// 简化2:简化括号
love = a-> {
System.out.println("I love you->" + a);
};
// 简化3:去掉花括号
love = a-> System.out.println("I love you->" + a);
/* 总结:
* 1. lambda 表达式只能有一行代码的情况下,才能简化为一行,如果有多行,就用代码块包裹
* 2. 前提是接口为函数式接口
* 3. 多个参数也可以去掉参数类型,要去掉就都去掉,必须加上括号
* */
}
}
interface Ilove {
void love(int a);
}
class Love implements Ilove {
@Override
public void love(int a) {
System.out.println("I love you-->" + a);
}
}
4. 线程状态
线程方法:
方法 | 说明 |
---|---|
setPriority(int newPriority) | 更改线程的优先级 |
static void sleep(long millis) | 在指定的毫秒数内让当前正在执行的线程休眠 |
void join() | 等待该线程终止 |
static void yield() | 暂停当前正在执行的线程对象,并执行其他线程 |
void interrupt() | 中断线程,别用这个方式 |
boolean isAlive() | 测试线程是否处于活动状态 |
4.1 停止线程
- 不推荐使用 JDK 提供的
stop()
、destroy()
方法【已废弃】 - 推荐线程自己停止下来
- 建议使用一个标志位进行终止变量,当
flag = false
,则终止线程运行
4.2 线程休眠
sleep(时间)
指定当前线程阻塞的毫秒数sleep
存在异常InterruptedException
sleep
时间达到后线程进入就绪状态sleep
可以模拟网络延时,倒计时等- 每一个对象都有一个锁,
sleep
不会释放锁
package com.feiye.state;
import java.text.SimpleDateFormat;
import java.util.Date;
// 模拟倒计时
public class TestSleep2 {
public static void main(String[] args) {
// 打印当前系统时间
Date startTime = new Date(System.currentTimeMillis()); // 获取系统当前时间
while (true) {
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
startTime = new Date(System.currentTimeMillis()); // 更新当前时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 模拟倒计时
public static void tenDown() throws InterruptedException {
int num = 10;
while(true) {
Thread.sleep(1000);
System.out.println(num--);
if (num<=0) {
break;
}
}
}
}
4.3 线程礼让
- 让当前正在执行的线程暂停,但不阻塞
- 将线程从运行状态转为就绪状态
- 让CPU重新调度,礼让不一定成功,看CPU心情
package com.feiye.state;
// 测试礼让线程
// 礼让不一定成功,看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() + "线程停止执行");
}
}
4.4 线程强制执行 JOIN
Join
合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞- 可以想象成插队
package com.feiye.state;
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 < 1000; i++) {
if (i == 200) {
thread.join(); // 插队
}
System.out.println("main" + i);
}
}
}
4.5 线程状态观测
- Thread.State
线程状态:
NEW
尚未启动的线程处于此状态RUNNABLE
在 Java 虚拟机中执行的线程处于此状态BLOCKED
被阻塞等待监视器锁定的线程处于此状态WAITING
正在等待另一个线程执行特定动作的线程处于此状态TIMED_WAITING
正在等待另一个线程执行动作达到指定等待时间的线程处于此状态TERMINATED
已退出的线程处于此状态
一个线程可以在给定时间点处于一个状态。这些状态是不反映任何操作系统线程状态的虚拟机状态
package com.feiye.state;
// 观察测试线程的状态
public class TestState {
public static void main(String[] args) throws InterruptedException {
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); // NEW
// 观察启动后
thread.start(); // 启动线程
state = thread.getState();
System.out.println(state); // Run
while (state != Thread.State.TERMINATED) { // 只要线程不终止,就一直输出状态
Thread.sleep(100);
state = thread.getState(); // 更新线程状态
System.out.println(state); // 输出状态
}
}
}
4.6 线程优先级
- Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行
- 线程的优先级用数字表示,范围从 1~10
Thread.MIN_PRIORITY = 1;
Thread.MAX_PRIORITY = 10;
Thread.NORM_PRIORITY = 5;
- 使用以下方式改变或获取优先级
getPriority().setPriority(int xxx)
- 优先级的设定建议再
start()
调度前
优先级低只意味着获得调度的概率低。并不是优先级低就不会被调用了,看CPU的调度
package com.feiye.state;
// 测试线程的优先级
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);
Thread t5 = new Thread(myPriority);
Thread t6 = new Thread(myPriority);
// 先设置优先级,再启动
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(4);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY); // MAX_PRIORITY = 10
t4.start();
}
}
class MyPriority implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
}
}
4.7 守护(daemon)线程
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕
- 虚拟机不用等待守护线程执行完毕
- 如:后台记录操作日志、监控内存、垃圾回收等待
package com.feiye.state;
// 测试守护线程
// 上帝守护你
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! ===============");
}
}
5. 线程同步机制
多个线程操作同一个资源
5.1 线程不安全案例
并发:同一个对象被多个线程同时操作
形成条件:队列 + 锁
- 由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制 synchronized,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可。存在以下问题:
- 一个线程持有锁会导致其他所有需要此锁的线程挂起
- 在多线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题
- 如果一个优先级高的线程等待一个优先级低的线程释放锁,会导致优先级倒置,引起性能问题
// UnsafeBuyTicket.java
package com.feiye.syn;
// 不安全的买票
// 线程不安全,有负数
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station, "啊?").start();
new Thread(station, "哦。").start();
new Thread(station, "奥。").start();
}
}
class BuyTicket implements Runnable {
// 票
private int ticketNums = 10;
boolean flag = true; // 外部停止方式
@Override
public void run() {
// 买票
while (flag) {
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void buy() throws InterruptedException {
// 判断是否有票
if (ticketNums <= 0) {
return;
}
// 模拟延时
Thread.sleep(100);
// 买票
System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
}
}
// UnsafeBank.java
package com.feiye.syn;
// 不安全的取钱
// 两个人去银行取钱,账户
public class UnsafeBank {
public static void main(String[] args) {
// 账户
Account account = new Account(100, "啊?");
Drawing you = new Drawing(account, 100, "哦");
Drawing me = new Drawing(account, 100, "奥");
you.start();
me.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() {
// 判断有没有钱
if (account.money - drawingMoney < 0) {
System.out.println(Thread.currentThread().getName() + "钱不够,取不了");
return;
}
// sleep 可以放大问题的发生性
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 卡内余额 = 余额 - 你取的钱
account.money = account.money - drawingMoney;
// 你手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name + "余额为:" + account.money);
// Thread.currentThread().getName() = this.getName()
System.out.println(this.getName() + "手里的钱:" + nowMoney);
}
}
// UnsafeList.java
package com.feiye.syn;
import java.util.ArrayList;
import java.util.List;
// 线程不安全的集合
public class UnsafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
5.2 同步方法及同步块
-
由于我们可以通过
private
关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized
关键字,包括两种用法:
synchronized
方法和synchronized
块// 同步方法: public synchronized void method(int args) {}
-
synchronized
方法控制对“对象”的访问,每个对象对应一把锁,每个synchronized
方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行缺陷:若将一个大的方法申明为 synchronized 将会影响效率
同步方法弊端:
方法里需要修改的内容才需要锁,锁的太多,浪费资源
同步块
- 同步块:
synchronized(Obj)
- Obj 称之为 同步监视器
- Obj 可以是任何对象,但推荐使用共享资源作为同步监视器
- 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是 this,就是这个对象本身,或者是 class
- 同步监视器的执行过程
- 第一个线程访问,锁定同步监视器,执行其中代码
- 第二个线程访问,发现同步监视器被锁定,无法访问
- 第一个线程访问完毕,解锁同步监视器
- 第二个线程访问,发现同步监视器没有锁,然后锁定并访问
// UnsafeBuyTicket.java
package com.feiye.syn;
// 不安全的买票
// 线程不安全,有负数
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station, "啊?").start();
new Thread(station, "哦。").start();
new Thread(station, "奥。").start();
}
}
class BuyTicket implements Runnable {
// 票
private int ticketNums = 10;
boolean flag = true; // 外部停止方式
@Override
public void run() {
// 买票
while (flag) {
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// synchronized 同步方法,锁的是 this
private synchronized void buy() throws InterruptedException {
// 判断是否有票
if (ticketNums <= 0) {
return;
}
// 模拟延时
Thread.sleep(100);
// 买票
System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
}
}
// UnsafeBank.java
package com.feiye.syn;
// 不安全的取钱
// 两个人去银行取钱,账户
public class UnsafeBank {
public static void main(String[] args) {
// 账户
Account account = new Account(1000, "啊?");
Drawing you = new Drawing(account, 100, "哦");
Drawing me = new Drawing(account, 100, "奥");
you.start();
me.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;
}
// 取钱
// synchronized 默认锁的是 this
@Override
public void run() {
// 锁的对象就是变化的量,需要增删改的对象
synchronized (account) {
// 判断有没有钱
if (account.money - drawingMoney < 0) {
System.out.println(Thread.currentThread().getName() + "钱不够,取不了");
return;
}
// sleep 可以放大问题的发生性
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 卡内余额 = 余额 - 你取的钱
account.money = account.money - drawingMoney;
// 你手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name + "余额为:" + account.money);
// Thread.currentThread().getName() = this.getName()
System.out.println(this.getName() + "手里的钱:" + nowMoney);
}
}
}
// UnsafeList.java
package com.feiye.syn;
import java.util.ArrayList;
import java.util.List;
// 线程不安全的集合
public class UnsafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
synchronized (list) {
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
JUC
package com.feiye.syn;
import java.util.concurrent.CopyOnWriteArrayList;
// 测试 JUC 安全类型的集合
public class TestJUC {
public static void main(String[] args) {
CopyOnWriteArrayList list = new CopyOnWriteArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()-> {
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
6. 死锁
多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或多个线程都在等待对方释放资源,都停止执行的情形。某一个同步块同时拥有**“两个以上对象的锁”**时,就可能会发生“死锁”问题
死锁避免方法
- 产生死锁的四个必要条件:
- 互斥条件:一个资源每次只能被一个进程使用
- 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源不放
- 不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺
- 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
我们只要想办法破除其中的任意一个或多个条件就可以避免死锁发生
package com.feiye.thread;
// 死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class DeadLock {
public static void main(String[] args) {
Makeup n1 = new Makeup(0, "灰姑娘");
Makeup n2 = new Makeup(1, "白雪公主");
n1.start();
n2.start();
}
}
// 口红
class Lipstick {
}
// 镜子
class Mirror {
}
class Makeup extends Thread {
// 需要的资源只有一份,用 static 来保证只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice; // 选择
String name; // 使用化妆品的人
Makeup (int choice, String name) {
this.choice = choice;
this.name = name;
}
@Override
public void run() {
// 化妆
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 化妆,互相持有对方的锁,就是需要拿到对方的资源
private void makeup() throws InterruptedException {
if (choice == 0) {
synchronized (lipstick) { // 获得口红的锁
System.out.println(this.name + "获得口红的锁");
Thread.sleep(1000);
}
synchronized (mirror) { // 一秒后想获得镜子
System.out.println(this.name + "获得镜子的锁");
}
} else {
synchronized (mirror) { // 获得镜子的锁
System.out.println(this.name + "获得镜子的锁");
Thread.sleep(2000);
}
synchronized (lipstick) { // 一秒后想获得口红
System.out.println(this.name + "获得口红的锁");
}
}
}
}
7. Lock 锁
- 从 JDK 5.0 开始,Java 提供了更强大的线程同步机制 —— 通过显式定义同步锁对象来实现同步。同步锁使用 Lock 对象充当
java.util.concurrent.locks.Lock
接口时控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个线程对 Lock 对象加锁,线程开始访问共享资源之前应先获得 Lock 对象ReentrantLock
类实现了 Lock,它拥有与synchronized
相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock
,可以显式加锁、释放锁
package com.feiye.senior;
import java.util.concurrent.locks.ReentrantLock;
// 测试Lock锁
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 ticketNums = 10;
// 定义Lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
try {
lock.lock(); // 加锁
if (ticketNums>0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
} else {
break;
}
} finally {
// 解锁
lock.unlock();
}
}
}
}
synchronized
与Lock
的对比
- Lock 是显式锁(手动开启和关闭锁,别忘记关闭锁)
synchronized
是隐式锁,出了作用域自动释放 - Lock 只有代码块锁,
synchronized
有代码块锁和方法锁 - 使用 Lock 锁,JVM 将花费较少的时间来调度线程,性能更好。并且具有更好的扩展性(提供更多的子类)
- 优先使用顺序
Lock > 同步代码块(已经进入了方法体,分配了相应资源)> 同步方法(在方法体之外)
class A {
private final ReentrantLock lock = new ReentrantLock();
public void m() {
lock.lock();
try {
// 保证线程安全的代码;
} finally {
lock.unlock();
// 如果同步代码有异常,要将 unlock() 写入 finally 语句块
}
}
}
8. 线程协作
生产者消费者问题
- Java提供了几个方法解决线程之间的通信问题
方法名 | 作用 |
---|---|
wait() | 表示线程一直等待,直到其他线程通知,与 sleep 不同,会释放锁 |
wait(long timeout) | 指定等待的毫秒数 |
notify() | 唤醒一个处于等待状态的线程 |
notifyAll() | 唤醒同一个对象上所有调用wait() 方法的线程,优先级别高的线程优先调度 |
注意:均是Object类的方法,都只能在同步方法或同步代码块中使用,否则会抛出异常 IllegalMonitorStateException
- 解决方式一:管程法
package com.feiye.senior;
// 测试:生产者消费者模型 --> 利用缓冲区解决:管程法
// 生产者,消费者,产品,缓冲区
public class TestPC {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Producer(container).start();
new Consumer(container).start();
}
}
// 生产者
class Producer extends Thread {
SynContainer container;
public Producer(SynContainer container) {
this.container = container;
}
// 生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("生产了" + i + "个产品");
container.push(new Product(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("消费了 --> " + container.pop().id + "个产品");
}
}
}
// 产品
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 product) {
// 如果容器满了,就需要等待消费者消费
if (count == 10) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 如果没有满,需要丢入产品
products[count] = product;
count++;
// 可以通知消费者消费了
this.notifyAll();
}
// 消费者消费产品
public synchronized Product pop() {
// 判断能否消费
if (count == 0) {
// 等待生产者生产,消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 如果可以消费
count--;
Product product = products[count];
// 消费完了,通知生产者生产
return product;
}
}
- 解决方法二:信号灯法
package com.feiye.senior;
// 测试生产者消费者问题2:信号灯法,标志位解决
public class TestPC2 {
public static void main(String[] args) {
TV tv = new TV();
new Player(tv).start();
new Audience(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 Audience extends Thread {
TV tv;
public Audience(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;
}
}
9. 线程池
- 背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大
- 思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中
可以避免频繁创建销毁、实现重复利用。类似生活中的公共交通工具 - 好处:
- 提高响应速度(减少了创建新线程的时间)
- 降低资源消耗(重复利用线程池中的线程,不需要每次都创建)
- 便于线程管理(……)
corePoolSize
: 核心池的大小maximumPoolSize
: 最大线程数keepAliveTime
: 线程没有任务时最多保持多长时间后会终止
- JDK 5.0 起提供了线程池相关 API:
ExecutorService
和Executors
ExecutorService
: 真正的线程池接口。常见子类ThreadPoolExecutor
void execute(Runnable command)
: 执行任务 / 命令,没有返回值,一般用来执行Runnable
<T>Future<T> submit(Callable<T> task)
: 执行任务,有返回值,一般用来执行Callable
void shutdown()
: 关闭连接池
Executors
: 工具类、线程池的工厂类,用于创建并返回不同类型的线程池
package com.feiye.senior;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// 测试线程池
public class TestPool {
public static void main(String[] args) {`
// 1. 创建服务,创建线程池
// newFixedThreadPool 参数为:线程池大小
ExecutorService service = Executors.newFixedThreadPool(10);
// 执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
// 2. 关闭连接
service.shutdown();
}
}
class MyThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + i);
}
}
}