线程创建
- 继承Thread类(重点)
- 实现Runnable接口(重点)
- 实现Callable接口(了解,以后重点)
继承Thread类
- 自定义线程类继承Thread类
- 重写run()方,编写线程执行体
- 创建线程对象,调用start()方法启动线程
// 创建线程方式: 继承Thread类 重写run()方法 调用start开启线程
public class TestThread1 extends Thread{
@Override
public void run() {
// run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("哈哈哈哈哈" + i);
}
}
public static void main(String[] args) {
// main线程
// 创建一个线程对象
TestThread1 testThread1 = new TestThread1();
// 调用start()方法开启线程
testThread1.start();
for (int i = 0; i < 20; i++) {
System.out.println("嘻嘻嘻" + i);
}
}
}
线程开启不一定立即执行,由CPU调度执行
网络下载图片例子:
// 练习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://huyaimg.msstatic.com/avatar/1020/24/c1420ad658150feb18eb0a3b55e9c6_180_135.jpg?1623559537?452739", "1.jpg");
TestThread2 t2 = new TestThread2("https://huyaimg.msstatic.com/avatar/1020/24/c1420ad658150feb18eb0a3b55e9c6_180_135.jpg?1623559537?452739", "2.jpg");
TestThread2 t3 = new TestThread2("https://huyaimg.msstatic.com/avatar/1020/24/c1420ad658150feb18eb0a3b55e9c6_180_135.jpg?1623559537?452739", "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方法出现问题");
}
}
}
实现Runnable接口
- 定义MyRunnable类实现
Runnable接口
- 实现
run()
方法,编写线程执行体 - 创建线程对象,调用
start()
方法
// 实现Runnable接口 重写run()方法 执行线程需要丢入Runnable接口的实现类 调用start()
public class TestThread3 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("调用了run()方法");
}
}
public static void main(String[] args) {
// 创建runnable接口的实现类对象
TestThread3 testThread3 = new TestThread3();
// 创建线程对象 通过线程对象来开启线程 代理
new Thread(testThread3).start();
for (int i = 0; i < 1000; i++) {
System.out.println("调用了main()方法");
}
}
}
继承Thread类:
- 子类继承Thread类具备多线程能力
- 启动线程:子类对象.start()
- 不建议使用:避免OOP单继承局限性
实现Runnable接口
- 实现Runnable具有多线程能力
- 启动线程:传入目标对象+Thread对象.start()
- 推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
实现Callable接口
- 实现Callable接口,选哟返回值类型
- 重写call方法,需要抛出异常
- 创建目标对象
- 创建执行服务:ExecutorService ser = Executor.newFixedThreadPool(1);
- 提交执行:Future result1 = ser.submit(t1);
- 获取结果:boolean r1 = result1.get();
- 关闭服务:ser.shutdownNow();
重写网络下载图片例子:
// 线程创建方式 实现Callable接口
public class TestCallable implements Callable<Boolean> {
// 下载图片线程的执行体
@Override
public Boolean call() throws Exception {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url, name);
System.out.println("下载了文件名为" + name);
return true;
}
private String url; // 网络图片地址
private String name; // 保存的文件名
public TestCallable(String url, String name) {
this.url = url;
this.name = name;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable t1 = new TestCallable("https://huyaimg.msstatic.com/avatar/1020/24/c1420ad658150feb18eb0a3b55e9c6_180_135.jpg?1623559537?452739", "1.jpg");
TestCallable t2 = new TestCallable("https://huyaimg.msstatic.com/avatar/1020/24/c1420ad658150feb18eb0a3b55e9c6_180_135.jpg?1623559537?452739", "2.jpg");
TestCallable t3 = new TestCallable("https://huyaimg.msstatic.com/avatar/1020/24/c1420ad658150feb18eb0a3b55e9c6_180_135.jpg?1623559537?452739", "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);
// 获取结果
boolean rs1 = r1.get();
boolean rs2 = r2.get();
boolean rs3 = r3.get();
System.out.println(rs1);
System.out.println(rs2);
System.out.println(rs3);
// 关闭服务
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方法出现问题");
}
}
}
callable的好处:
- 可以定义返回值
- 可以抛出异常
静态代理
// 静态代理模式总结:
// 真实对象和代理对象都要实现同一个接口
// 代理对象要代理真实角色
// 好处:
// 代理对象可以做好多真实对象做不了的事情
// 真实对象专注做自己的事情
public class StaticProxy {
public static void main(String[] args) {
You you = new You(); // 你要结婚
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 after() {
System.out.println("结婚之后");
}
private void before() {
System.out.println("结婚之前");
}
}
多线程Runnable底层原理:
// 静态代理模式总结:
// 真实对象和代理对象都要实现同一个接口
// 代理对象要代理真实角色
new Thread( () -> System.out.println("我爱你") ).start();
new WeddingCompany(new You()).HappyMarry();
- Thread类相当于是代理,它和真实对象都实现了Runnable接口
- Thread代理的真实的Runnable接口
() -> System.out.println("我爱你")
- HappyMarry()相当于start()
Lambda表达式
- 避免匿名内部类定义过多
- 可以让代码看起来简洁
- 去掉了一堆没有意义的代码,只留下了核心的逻辑
什么是函数式接口?
任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口。
public interface Runnable {
public abstract void run();
}
对于函数式接口,我们可以使用lambda表达式来创建该接口的对象
// 推导Lambda表达式
public class TestLambda {
// 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");
}
}
lambda简化:
love = (int a) -> {
System.out.println("I Love You" + a);
};
love.love(5);
// 简化1:去掉参数类型
love = (a) -> {
System.out.println("I Love You" + a);
};
love.love(6);
// 简化2:简化()
love = a -> {
System.out.println("I Love You" + a);
};
love.love(7);
// 简化3:去掉{}
love = a -> System.out.println("I Love You" + a);
love.love(8);
// 总结 lambda表达式只能有一行代码的情况下才能简化为一行 如果有多行那么就用代码块包裹
// 前提是函数式接口
// 多个参数也能去掉参数类型 要去掉就全部去掉 必须加上()
线程状态
线程停止
JDK提供的stop()、destroy()方法已经废弃,不推荐使用
建议使用一个标志位进行终止变量,当flag=false时,则终止线程运行。
// 测试停止线程
// 1.建议线程正常停止 --> 利用次数,不建议死循环
// 2.建议使用标志位 --> 设置一个标志位
// 3.不要使用stop()或destroy()等过时或JDK不建议的方法
public class TestStop implements Runnable{
// 1.设置一个标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag) {
System.out.println("run...Thread" + i++);
}
}
// 2.设置一个公开的方法停止线程,转换标志位
public void stop() {
this.flag = false;
}
public static void main(String[] args) {
TestStop stop = new TestStop();
new Thread(stop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main线程" + i);
if (i == 900) {
// 调用stop()方法切换标志位 停止线程
stop.stop();
System.out.println("线程运行停止了");
}
}
}
}
线程休眠
- sleep指定当前线程阻塞的毫秒数
- sleep存在异常InterruptedException
- sleep时间达到后线程进入就绪状态
- sleep可以模拟网络延时,倒计时等
- 每一个对象都有一个锁,sleep不会释放锁
public class TestSleep2 {
public static void main(String[] args) {
// 模拟倒计时
try {
tenDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 打印当前系统时间
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;
}
}
}
线程礼让
- 礼让线程,让当前正在执行的线程暂停,但不阻塞
- 将线程从运行状态转换为就绪状态
- 让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() + "线程停止执行");
}
}
线程强制执行
Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞
// 测试Join方法 插队
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("vip is coming" + 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 < 500; i++) {
if (i == 50) {
thread.join(); //插队
}
System.out.println("main" + i);
}
}
}
线程状态测试
// 观察测试线程状态
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); //RUNNABLE
while (state != Thread.State.TERMINATED) { //只要线程不终止 就一直输出状态
Thread.sleep(100);
state = thread.getState(); // 更新状态
System.out.println(state); //TIMED_WAITING
}
}
}
线程进入死亡状态后,就不能再次启动
线程优先级
- Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。
- 线程的优先级用数字表示,范围从1~10
- Thread.MIN_PRIORITY = 1;
- Thread.MAX_PRIORITY = 10;
- Thread.NORM_PRIORITY = 5;
- 使用以下方式改变或者获取优先级
- getPriority()
- setPriority(int xxx)
// 测试线程的优先级
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); //10
t4.start();
t5.setPriority(8);
t5.start();
t6.setPriority(7);
t6.start();
}
}
class MyPriority implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "--> " + Thread.currentThread().getPriority());
}
}
线程优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看CPU的调度。
守护线程
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕
- 虚拟机不用等待守护线程执行完毕
- 如后台记录操作日志,监控内存,垃圾回收等待…
// 测试守护线程
// 上帝守护你
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("人挂了");
}
}
当用户线程结束后,上帝线程依旧执行,是因为虚拟机停止需要一点时间。
线程同步
多个线程操作同一个资源 如 抢火车票、两个银行同时取钱…
线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程再使用。
由于同一个进程的多个线程共享同一块存储空间,在带来方便的同时也带来了访问冲突的问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可。存在以下问题:
- 一个线程持有锁会导致其他所有需要此锁的线程挂起
- 在多线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题
- 如果一个优先级高的线程等待一个优先级低的线程释放锁,会导致优先级倒置,引起性能问题
不安全案例
// 不安全的买票
// 线程不安全 有复数
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;
private boolean flag = true; // 外部停止方式
@Override
public void run() {
while (flag) {
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void buy() throws InterruptedException {
// 判断是否有票
if (ticketNums <= 0) {
flag = false;
return;
}
// 模拟延时
Thread.sleep(100);
// 买票
System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNums-- + "张票");
}
}
// 不安全的取钱
public class UnSafeBank {
public static void main(String[] args) {
// 账户
Account account = new Account(100, "基金");
Drawing you = new Drawing(account, 50, "你");
Drawing girlFriend = new Drawing(account, 100, "girlFriend");
you.start();
girlFriend.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);
}
}
// 线程不安全的集合
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(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
两个线程在list的同一个位置进行操作,其中一个线程将另一个线程的操作位置内容覆盖
同步方法及同步块
由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包括两种用法:synchronized方法和synchronized块
synchronized方法控制对“对象”的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,知道该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行。缺陷:若将一个大的方法申明为synchronized 将会影响效率。
// 不安全的买票
// 线程不安全 有复数
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;
private 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) {
flag = false;
return;
}
// 模拟延时
Thread.sleep(100);
// 买票
System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNums-- + "张票");
}
}
同步块:synchronized(Obj){ }
Obj称为同步监视器,Obj可以是任何对象,但是推荐使用共享资源作为同步监视器。同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者是class
同步监视器的执行过程:
- 第一个线程访问,锁定同步监视器,执行其中的代码
- 第二个线程访问,发现同步监视器被锁定,无法访问
- 第一个线程访问完毕,解锁同步监视器
- 第二个线程访问,发现同步监视器没有锁,然后锁定并访问
// 不安全的取钱
public class UnSafeBank {
public static void main(String[] args) {
// 账户
Account account = new Account(1000, "基金");
Drawing you = new Drawing(account, 50, "你");
Drawing girlFriend = new Drawing(account, 100, "girlFriend");
you.start();
girlFriend.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);
}
}
}
// 线程不安全的集合
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(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
JUC中的安全集合
// 测试JUC安全类型的集合
public class TestJUC {
public static void main(String[] args) {
CopyOnWriteArrayList<String> 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());
}
}
死锁
多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或多个线程都在等待对方释放资源,都停止执行的情况。某一个同步块同时拥有“两个以上对象的锁”时,就可能会发生“死锁”的问题。
产生死锁的四个必要条件:
- 互斥条件:一个资源每次只能被一个进程使用
- 请求和保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放
- 不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺
- 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
// 死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class DeadLock {
public static void main(String[] args) {
Makeup g1 = new Makeup(0, "翠花");
Makeup g2 = new Makeup(1, "狗蛋");
g1.start();
g2.start();
}
}
// 口红
class Lipstick {
}
// 镜子
class Mirror {
}
// 化妆
class Makeup extends Thread {
// 需要的资源只有一份,用static来保证只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice; //选择
String girlName; //使用的人
Makeup(int choice, String girlName) {
this.choice = choice;
this.girlName = girlName;
}
@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.girlName + "口红");
Thread.sleep(1000);
}
// 一秒钟后想获得镜子
synchronized (mirror) {
System.out.println(this.girlName + "镜子");
}
}else {
// 获得镜子的锁
synchronized (mirror) {
System.out.println(this.girlName + "镜子");
Thread.sleep(2000);
}
// 一秒钟后想获得口红
synchronized (lipstick) {
System.out.println(this.girlName + "口红");
}
}
}
}
Lock锁
通过显式定义同步锁对象来实现同步,同步锁使用Lock对象充当
java.util.concurrent.locks.Lock接口是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象
可重入锁ReentrantLock类实现了Lock,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显式加锁、释放锁。
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 > 同步代码块(已经进入了方法体,分配了相应资源) > 同步方法(在方法体之外)
线程协作
生产者和消费者问题
这是一个线程同步问题,生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件
- 对于生产者,没有生产产品之前,要通知消费者等待,而生产产品之后,又要马上通知消费者消费
- 对于消费者,在消费之后,要通知生产者已经结束消费,需要生产新的产品以供消费
- 在生产者和消费者问题中,synchronized是不够的
- synchronized 可阻止并发更新同一个共享资源,实现了同步
- synchronized 不能用来实现不同线程之间的消息传递(通信)
管程法
// 测试生产者消费者模型,利用缓冲区解决 管程法
// 生产者 消费者 产品 缓冲区
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 Chicken(i));
System.out.println("生产了" + 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 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();
}
}
// 如果没有满 就需要放入产品
chickens[count] = chicken;
count++;
// 可以通知消费者消费
this.notifyAll();
}
// 消费者消费产品
public synchronized Chicken pop() {
// 判断能否消费
if (count == 0) {
// 等待生产者生产 消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 如果可以消费
count--;
Chicken chicken = chickens[count];
// 通知生产者生产
this.notifyAll();
return chicken;
}
}
信号灯法
// 测试生产者消费者问题2 信号灯法 标志位解决
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 {
// 演员表演的时候 观众等待
// 观众观看的时候演员等待
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;
}
}
线程池
背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大
思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。类似生活中的公共交通工具。
好处:
- 提高相应速度(减少了创建新线程的时间)
- 降低资源消耗(重复利用线程池中线程,不需要每次都创建)
- 便于线程管理
- corePoolSIze:核心池的大小
- maximumPoolSize:最大线程数
- keepAliveTime:线程没有任务时最多保持多长时间后会终止
// 测试线程池
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() {
System.out.println(Thread.currentThread().getName());
}
}
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;
}
}
## 线程池
背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大
思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。类似生活中的公共交通工具。
好处:
1. 提高相应速度(减少了创建新线程的时间)
2. 降低资源消耗(重复利用线程池中线程,不需要每次都创建)
3. 便于线程管理
- corePoolSIze:核心池的大小
- maximumPoolSize:最大线程数
- keepAliveTime:线程没有任务时最多保持多长时间后会终止
```java
// 测试线程池
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() {
System.out.println(Thread.currentThread().getName());
}
}