Java多线程个人笔记
Java多线程详解
概述
三种创建方式
Thread class
- 自定义线程类继承Thread类
- 重写run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程
- 总结:线程开启不一定立即执行,有CPU调度执行
package com;
// 创建线程方式1:继承Thread类。重写run()方法,调用start开启线程
// 总结:线程开启不一定立即执行,有CPU调度执行
public class TestThread extends Thread {
@Override
public void run() {
// run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("SIU~~~`");
}
}
public static void main(String[] args) {
// main线程(主线程)
TestThread testThread1 = new TestThread(); // 创建一个线程对象
testThread1.start(); // 调用start方法开启线程
for (int i = 0; i < 2000; i++) {
System.out.println("siusiusiu~~~" + i); // 中间会穿插输出SIU
}
}
}
package com.Siu.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 fileName;
public TestThread2(String url, String fileName) {
this.url = url;
this.fileName = fileName;
}
@Override
public void run() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(this.url, this.fileName);
System.out.println("下载了文件:" + this.fileName);
}
public static void main(String[] args) {
TestThread2 t1 = new TestThread2("https://bdimg6.qunliao.info/fastdfs6/M00/AA/98/rBUESWNC2ZWATTiOAAMqUKlwr9Y924.jpg", "懂球帝1.jpg");
TestThread2 t2 = new TestThread2("https://bdimg6.qunliao.info/fastdfs6/M00/AA/97/rBUCgGNC2i-ALQyJAADSixvjG_4811.jpg", "懂球帝2.jpg");
TestThread2 t3 = new TestThread2("https://bdimg6.qunliao.info/fastdfs6/M00/AA/B5/rBUESWNC3HKAPrrZABSiXdnvkig891.png", "懂球帝3.png");
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();
System.out.println("IO异常,downloader方法出现问题");
}
}
}
Runnable接口
- 定义MyRunnable类实现Runnable接口
- 定义run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程
package com.Siu.Demo01;
// 创建线程方式2:实现runnable接口,重写run方法,执行线程需要丢入runnable接口实现类,调用start方法
public class TestThread3 implements Runnable{
@Override
public void run() {
// run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("SIU~~~`");
}
}
public static void main(String[] args) {
// 创建runnable接口的实现类对象
TestThread3 testThread3 = new TestThread3();
// 创建线程对象,通过线程对象来开启线程,代理
new Thread(testThread3).start();
for (int i = 0; i < 2000; i++) {
System.out.println("siusiusiu~~~" + i); // 中间会穿插输出SIU
}
}
}
小结:
- 继承Thread类
- 子类继承thread类具备多线程能力
- 启动线程:子类对象.start()
- 不建议使用:避免OPP单继承局限性
- 实现Runnable接口
- 实现接口Runnable具有多线程能力
- 启动线程:传入目标对象+Thread对象.star()
- 推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
并发问题
package com.Siu.Demo01;
// 多个线程同时操作同一个对象
// 买火车票的例子
// 发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱
public class TestThread4 implements Runnable {
// 票数
private int ticketsNum = 10;
@Override
public void run() {
do {
try {
Thread.sleep(200); // 模拟延时
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "--->拿到了第" + ticketsNum-- + "张票.");
} while (ticketsNum > 0);
}
public static void main(String[] args) {
TestThread4 ticket = new TestThread4();
new Thread(ticket, "骡子").start();
new Thread(ticket, "球玊").start();
new Thread(ticket, "龌騾").start();
}
}
案例:龟兔赛跑—Race
- 首先来个赛道距离,然后要离终点越来越近
- 判断比赛是否结束
- 打印出获胜者
- 龟兔赛跑开始
- 故事中是乌龟赢得,兔子需要睡觉,所以需要模拟兔子睡觉
- 最终乌龟win
package com.Siu.Demo01;
// 模拟龟兔赛跑
public class Race implements Runnable {
// 胜利者
private static String winner;
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
// 模拟兔子休息
if (Thread.currentThread().getName().equals("rabbit") && i % 10 == 0) {
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 判断比赛是否结束
boolean flag = isGameOver(i);
// 如果比赛结束,就停止程序
if (flag) {
break;
}
System.out.println(Thread.currentThread().getName() + "-->跑了" + i + "步");
}
}
private boolean isGameOver(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, "rabbit").start();
new Thread(race, "tortoise").start();
}
}
Callable接口(了解即可)
- 实现Callable接口,需要返回值类型
- 重写call方法,需要抛出异常
- 创建目标对象
- 创建执行服务:ExecutorService ser = Executor.newFixedThreadPool(1);
- 提交执行:Future
result1 = ser.submit(t1); - 获取结果:boolean r1 = result1.get()
- 关闭服务:ser.shutdownNow();
package com.Siu.Demo02;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
// 创建方式3:实现callable接口
public class TestCallable implements Callable<Boolean> {
private String url;
private String fileName;
public TestCallable(String s, String s1) {
this.url = s;
this.fileName = s1;
}
@Override
public Boolean call() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(this.url, this.fileName);
System.out.println("下载了文件:" + this.fileName);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable t1 = new TestCallable("https://bdimg6.qunliao.info/fastdfs6/M00/AA/98/rBUESWNC2ZWATTiOAAMqUKlwr9Y924.jpg", "懂球帝1.jpg");
TestCallable t2 = new TestCallable("https://bdimg6.qunliao.info/fastdfs6/M00/AA/97/rBUCgGNC2i-ALQyJAADSixvjG_4811.jpg", "懂球帝2.jpg");
TestCallable t3 = new TestCallable("https://bdimg6.qunliao.info/fastdfs6/M00/AA/B5/rBUESWNC3HKAPrrZABSiXdnvkig891.png", "懂球帝3.png");
// 创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
// 提交执行
Future<Boolean> result1 = ser.submit(t1);
Future<Boolean> result2 = ser.submit(t2);
Future<Boolean> result3 = ser.submit(t3);
// 获取结果
boolean r1 = result1.get();
boolean r2 = result2.get();
boolean r3 = result3.get();
// 关闭服务
ser.shutdownNow();
System.out.println(r1);
System.out.println(r2);
System.out.println(r3);
}
}
// 下载器
class WebDownloader {
// 下载方法
public void downloader(String url, String fileName) {
try {
FileUtils.copyURLToFile(new URL(url), new File(fileName));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloader方法出现问题");
}
}
}
静态代理
package com.Siu;
//静态代理总结
//真实对象和代理对象要实现同一个接口
//代理对象要代理真实角色
//好处:
//代理对象可以做很多真实对象做不了的事情
//真实对象专注做自己的事情
public class StaticProxy {
public static void main(String[] args) {
// WeddingCompany weddingCompany=new WeddingCompany(new 0000000000 You());
// weddingCompany.HappyMarry();
new WeddingCompany(new You()).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("张灯结彩,布置婚礼");
}
}
lambda表达式
- λ希腊字母表中排序第11位的字母,英文名称lambda
- 避免匿名内部类定义过多
- 其实质属于函数式编程的概念
- 函数式接口
- 任何接口,如果只包含唯一一个抽象方法,那么他就是一个函数式接口
- 对于函数式接口,通过lambda表达式来创建该接口的对象
lambda 表达式的语法格式如下:
(parameters) -> expression 或 (parameters) ->{ statements; }
无参
package com.Siu.Demo03;
// 推到lambda表达式
public class TestLambda1 {
// 静待内部类
static class Like2 implements ILikle {
@Override
public void lambda() {
System.out.println("I like lambda2");
}
}
public static void main(String[] args) {
ILikle like = new Like();
like.lambda();
like = new Like2();
like.lambda();
// 局部内部类
class Like3 implements ILikle {
@Override
public void lambda() {
System.out.println("I like lambda3");
}
}
like = new Like3();
like.lambda();
// 匿名内部类,没有类名,必须借助接口或父类
like = new ILikle() {
@Override
public void lambda() {
System.out.println("I like lambda4");
}
};
like.lambda();
// lambda简化
like = ()-> {
System.out.println("I like lambda5");
};
like.lambda();
}
}
// 定义一个函数式接口
interface ILikle {
void lambda();
}
class Like implements ILikle {
@Override
public void lambda() {
System.out.println("I like lambda");
}
}
带参
package com.Siu.Demo03;
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);
};
love.love(2);
// 简化2:去参类型和括号
love = a -> {
System.out.println("I love you " + a);
};
love.love(2);
// 简化3:去花括号
love = a -> System.out.println("I love you " + a);
love.love(2);
// 总结:
// 只有一行代码,lambda表达式可以去花括号
// 前提是接口是函数式接口(接口里必须只能有一个接口)
// 多个参数,也可以去掉参数类型,但是不能去括号
}
}
interface Ilove {
void love(int a);
}
线程状态
线程方法
线程停止
package com.Siu.state;
// 测试stop
// 建议线程正常停止-->>利用次数,不建议死循环
// 建议使用标志位-->>设置一个标志位
// 不要使用stop或者destroy等过时或jdk不推荐使用的方法
public class TestStop implements Runnable {
// 设置一个标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag) {
System.out.println("Run and Siu~" + i++);
}
}
// 设置一个公开的方法停止线程,转换标志位
public void stop() {
this.flag = false;
}
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main " + i);
if (i == 900) {
// 调用stop方法切换标志位,让县城停止
testStop.stop();
System.out.println("不要再Siu~~~了");
}
}
}
}
线程休眠
- sleep指定当前线程阻塞的毫秒数
- sleep存在异常InterruptException
- sleep时间打倒后线程进入就绪状态
- sleep可以模拟网络延时,倒计时等
- 每个对象都有一个🔒,sleeo不会释放锁
package com.Siu.state;
import java.text.SimpleDateFormat;
import java.util.Date;
// 模拟倒计时
public class TestSleep2 {
public static void main(String[] args) {
// try {
// tenDown();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// 打印当前系统time
while (true){
try {
Date startTime = new Date(System.currentTimeMillis()); // 更新当前时间
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
} 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;
}
}
}
}
线程礼让
- 线程礼让,让当前正在执行的线程暂停,danbuzuse
- 让线程从运行咋黄台转为就绪状态
- 让CPU重新调度,礼让不一定成功
package com.Siu.state;
// 测试礼让现场
// yield不一定成功
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() + "线程开始siu~");
Thread.yield(); // 礼让
System.out.println(Thread.currentThread().getName() + "线程停止siu~");
}
}
线程强制执行—join
- join可以合并线程,待此线程执行完成后,在执行其他线程,其他线程阻塞
- 就是插队
package com.Siu.state;
// 测试join方法 (插队)
public class TestJoin implements Runnable {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("躲开!siu~~~");
}
}
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);
}
}
}
线程状态观测
- Thread.State
- 线程状态。线程可以处于以下状态之一:
NEW
尚未启动的线程处于此状态。RUNNABLE
在Java虚拟机中执行的线程处于此状态。BLOCKED
被阻塞等待监视器锁定的线程处于此状态。WAITING
正在等待另一个线程执行特定动作的线程处于此状态。TIMED_WAITING
正在等待另一个线程执行动作达到指定等待时间的线程处于此状态。TERMINATED
已退出的线程处于此状态。
- 线程状态。线程可以处于以下状态之一:
一个线程可以在给定时间点处于一个状态。 这些状态是不反映任何操作系统线程状态的虚拟机状态。
package com.Siu.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); // 输出状态
}
}
}
线程优先级
-
Java为线程类提供了10个优先级
-
优先级可以用整数1-10表示,超过范围会抛出异常
-
主线程默认优先级为5
-
优先级常量
- MAX_ PRIORITY :线程的最高优先级10
- MIN_ PRIORITY :线程的最低先级1
- NORM_ PRIORITY :线程的默认优先级5
-
优先级相关的方法
-
public int getPriority() *//获取线程优先级的方法* public void setPriority(int newPriority) *//设置线程优先级的方法*
-
package com.Siu.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);
t4.start();
// t5.setPriority(-1);
// t5.start();
// t6.setPriority(11);
// t6.start();
}
}
class MyPriority implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
}
}
守护线程
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕
- 虚拟机不用等待守护线程执行完毕
- ex:后台记录操作,监控内存,垃圾分类等待
package com.Siu.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
thread.start();
new Thread(you).start(); // 用户线程启动
}
}
// 上帝
class God implements Runnable{
@Override
public void run() {
while(true){
System.out.println("上帝开始siu");
}
}
}
// you
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 35600; i++) {
System.out.println("我siu故我在");
}
System.out.println("========不siu了========");
}
}
线程同步
多个线程操作同一个资源
并发:同一个对象被多个线程同时操作
多个线程访问同一个对象,并且某些线程还想修改这个对象,多个同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一给线程再使用
三大不安全案例
案例1
package com.Siu.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) {
flag = false;
return;
}
// 模拟演示
Thread.sleep(100);
// 买票
System.out.println(Thread.currentThread().getName() + ticketNums-- + "");
}
}
案例2
package com.Siu.Syn;
// 不安全的取钱
// 两个人去银行取钱,账户
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(1_000_000, "网吧余额");
Drawing you = new Drawing(account, 500_000, "骡子");
Drawing wife = new Drawing(account, 1_000_000, "乔治娜");
new Thread(you).start();
new Thread(wife).start();
}
}
// Account
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.drawingMoney = drawingMoney;
this.account = account;
}
// 取钱的操作
@Override
public void run() {
// 判断有没有钱
if (account.money - drawingMoney < 0) {
System.out.println(Thread.currentThread().getName() + "siu( $ _ $ )不够");
return;
}
try {
Thread.sleep(1000); // sleep可以方法问题的发生性
} catch (InterruptedException e) {
e.printStackTrace();
}
account.money -= drawingMoney;
nowMoney += drawingMoney;
System.out.println(account.name + "余额为:" + account.money);
System.out.println(this.getName() + "手里的钱:" + nowMoney);
}
}
案例3
package com.Siu.Syn;
import java.util.ArrayList;
import java.util.List;
// 线程不安全的集合
public class UnsafeList {
public static void main(String[] args) throws InterruptedException {
List<String> list = new ArrayList<>();
for (int i = 0; i < 10_000; i++) {
new Thread(() -> {
list.add(Thread.currentThread().getName());
}).start();
}
Thread.sleep(3000);
System.out.println(list.size());
}
}
同步方法:
-
由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包括两种和用法:synchronized方法和synchronized块
-
public synchronized void method(int args){}
-
-
synchronized方法控制对“对象”的访问,每个对象对应一把锁,每个synchronized方法都必须调用该方法的对应🔒所才能执行,否则线程会阻塞,方法一旦执行,就独占该🔒,知道该方法返回才释放🔒,后面被阻塞的线程才能获得这个锁,继续执行
-
若将一个大方法声明为synchronized,会大大影响效率
同步块
安全买票:
package com.Siu.Syn;
// 安全的买票
public class SafeBuyTicket {
public static void main(String[] args) {
BuyTicket1 station = new BuyTicket1();
new Thread(station, "骡子").start();
new Thread(station, "龌騾").start();
new Thread(station, "球玊").start();
}
}
class BuyTicket1 implements Runnable {
// 票
private int ticketNums = 10;
boolean flag = true; // 外部停止方式
@Override
public void run() {
// 买票
while (flag) {
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 同步方法,🔒的是this
private synchronized void buy() throws InterruptedException {
// 判断是否有票
if (ticketNums <= 0) {
flag = false;
return;
}
// 买票
System.out.println(Thread.currentThread().getName() + ticketNums-- + "");
}
}
安全取钱:
package com.Siu.Syn;
// 不安全的取钱
// 两个人去银行取钱,账户
public class SafeBank {
public static void main(String[] args) {
Account1 account1 = new Account1(1_000_000, "网吧余额");
Drawing1 you = new Drawing1(account1, 500_000, "骡子");
Drawing1 wife = new Drawing1(account1, 1_000_000, "乔治娜");
new Thread(you).start();
new Thread(wife).start();
}
}
// Account
class Account1 {
int money; // 余额
String name; // 卡名
public Account1(int money, String name) {
this.money = money;
this.name = name;
}
}
// 银行:模拟取款
class Drawing1 extends Thread {
Account1 account; // 账户
// 取了多少钱
int drawingMoney;
// 手里有多少钱
int nowMoney;
public Drawing1(Account1 account, int drawingMoney, String name) {
super(name); // 线程名字
this.drawingMoney = drawingMoney;
this.account = account;
}
// 取钱的操作
@Override
public void run() {
synchronized (account) {
// 判断有没有钱
if (account.money - drawingMoney < 0) {
System.out.println(Thread.currentThread().getName() + "siu( $ _ $ )不够");
return;
}
try {
Thread.sleep(1000); // sleep可以方法问题的发生性
} catch (InterruptedException e) {
e.printStackTrace();
}
account.money -= drawingMoney;
nowMoney += drawingMoney;
System.out.println(account.name + "余额为:" + account.money);
System.out.println(this.getName() + "手里的钱:" + nowMoney);
}
}
}
死锁
package com.Siu.thread;
public class DeadLock {
public static void main(String[] args) {
MakeUp girl1 = new MakeUp(0, "马约尔佳");
MakeUp girl2 = new MakeUp(1, "乔治娜");
girl1.start();
girl2.start();
}
}
// 口红
class Lipstick {
}
// 镜子
class Mirror {
}
class MakeUp extends Thread {
// 需要的资源只有一份,用static保证只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice; // 选择
String girlName; // person using 化妆品
MakeUp(int choice, String girlName) {
this.choice = choice;
this.girlName = girlName;
}
@Override
public void run() {
// 化妆
try {
makup();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
// 化妆,互相持有对方的🔒,需要拿到对方的资源
private void makup() throws InterruptedException {
if (choice == 0) {
synchronized (lipstick) { // 获得口红的所
System.out.println(this.girlName + "获得口红的🔒");
Thread.sleep(1000);
// synchronized (mirror) { // 一秒钟后,获得镜子的🔒
// System.out.println(this.girlName + "获得镜子的🔒");
// }
}
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 + "获得口红的🔒");
// }
}
synchronized (lipstick) { // 一秒钟后,获得口红的🔒
System.out.println(this.girlName + "获得口红的🔒");
}
}
}
}
死锁避免方法
Lock🔒
synchronized与Lock对比
- Lock是显式锁(手动开启和关闭锁),synchronized是隐式锁,初了作用域自动释放
- lock只有代码块锁,synchronized有代码块锁和方法锁
- 使用lock🔒,JVM将花费较少时间来调度线程,性能更好,并且具有更好的扩展性(提供更多子类)
- 优先使用顺序
- lock>同步代码块(已经进入方法体,分配了相应资源)>同步方法(在方法体之外)
线程协作
生产者消费者模式
线程通信
分析
Java方法
解决方法1
package com.Siu.thread;
// 测试生产者消费者模型->利用缓冲区解决:管程法
// 生产者,消费者,产品,缓冲区
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 + "只ji");
container.push(new Chicken(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) {
// 如果容器满了,就需要等待消费
while (count == chickens.length) {
// 通知消费者消费,生产等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 如果没有满,需要丢入产品
chickens[count] = chicken;
count++;
this.notify();
// 可以通知消费者消费了
}
// 消费者消费产品
public synchronized Chicken pop() {
// 判断是否可以消费
while (count == 0) {
// 等待生产者生产,消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 如果可以消费
count--;
Chicken chicken = chickens[count];
this.notify();
// 如果吃完了,通知生产者生产
return chicken;
}
}
解决方法2
package com.Siu.thread;
// 测试生产者消费者问题2:信号灯法,标志为解决
public class TestPC2 {
public static void main(String[] args) {
Show show = new Show();
new Player(show).start();
new Watcher(show).start();
}
}
// 生产者:演员
class Player extends Thread {
Show show;
public Player(Show show) {
this.show = show;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if (i % 2 == 0) {
this.show.play("siu播放中");
} else this.show.play("广告");
}
}
}
// 消费者:观众
class Watcher extends Thread {
Show show;
public Watcher(Show show) {
this.show = show;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
this.show.watch();
}
}
}
// 产品:节目
class Show {
// 演员表演时,观众等待
// 观众观看时,演员等待
String show; // 表演的节目
boolean flag = true;
// 表演
public synchronized void play(String show) {
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演了" + show);
// 通知观众观看
this.notify(); // 通知唤醒
this.show = show;
this.flag = !flag;
}
// 观看
public synchronized void watch() {
if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观看了:" + show);
// 通知演员表演
this.notify();
this.flag = !flag;
}
}
线程池
package com.Siu.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// 测试线程池
public class TestPool {
public static void main(String[] args) {
// 创建服务,创建线程池
// newFixedThreadPool 参数为线程池大小
ExecutorService service = Executors.newFixedThreadPool(10);
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
// 关闭连接
service.shutdown();
}
}
class MyThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName());
}
}
}
总结
package com.Siu.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
// 回顾线程的创建
public class ThreadNew {
public static void main(String[] args) {
new MyThread1().start();
new Thread(new MyThread2()).start();
FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyThread3());
new Thread(futureTask).start();
try {
Integer integer = futureTask.get();
System.out.println(integer);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
// 1.继承thread类
class MyThread1 extends Thread {
@Override
public void run() {
System.out.println("MyThread1");
}
}
// 2.实现Runnable接口
class MyThread2 implements Runnable {
@Override
public void run() {
System.out.println("MyThread2");
}
}
// 3.实现Callable接口
class MyThread3 implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("MyThread3");
return 100;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)