多线程详解
多线程
1.线程简介
2.线程创建(重点)
1.集成Thread类(重点)
package com.jihu.Thread01;
//创建多线程方式一: 继承Thread类,重写run()方法,调用start开启线程
//总结: 注意,线程开启不一定立即执行,由CPU调度执行
public class Demo01 extends Thread {
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 200; i++) {
System.out.println("我是run方法");
}
}
public static void main(String[] args) {
//main线程,主线程
//创建一个线程对象
Demo01 demo01 = new Demo01();
//调用start()方法开启线程
demo01.start();
for (int i = 0; i < 1000; i++) {
System.out.println("我在学习多线程");
}
}
}
输出结果: (部分代码)
我在学习多线程
我在学习多线程
我是run方法
我是run方法
我是run方法
我是run方法
我在学习多线程
我在学习多线程
我在学习多线程
我在学习多线程
网络图片下载 案例
需要导入 commons-io-2.6.jar这个包
package com.jihu.Thread01;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//练习Thread,实现多线程同步下载图片
public class TestThread02 extends Thread {
private String url; //网络图片地址
private String name; //保存的文件名
public TestThread02(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) {
TestThread02 t1 = new TestThread02("https://148342yin-1316298725.cos.ap-beijing.myqcloud.com/images/blog/20220306175925.png","1.png");
TestThread02 t2 = new TestThread02("https://148342yin-1316298725.cos.ap-beijing.myqcloud.com/images/blog/20220306175654.png","2.png");
TestThread02 t3 = new TestThread02("https://148342yin-1316298725.cos.ap-beijing.myqcloud.com/images/blog/20220305194641.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方法出现问题");
}
}
}
输出结果:
下载了文件名为:1.png
下载了文件名为:3.jpg
下载了文件名为:2.png
2.实现Runnable(重点)
package com.jihu.Thread01;
//创建线程方式2:实现Runnable接口,重写run方法,执行线程需要丢入runnable接口实现类,调用start方法
public class TestThread03 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
//run方法线程体
System.out.println("我是run()方法");
}
}
public static void main(String[] args) {
//创建runnable接口的实现类对象
TestThread03 testThread03 = new TestThread03();
//创建线程对象,通过线程对象来开启我们的线程,代理
// Thread thread = new Thread();
// thread.start();
new Thread(testThread03).start();
for (int i = 0; i < 100; i++) {
System.out.println("我在学习多线程");
}
}
}
输出结果
我在学习多线程
我在学习多线程
我是run()方法
我是run()方法
我是run()方法
在学习多线程
在学习多线程
小结
3.初识并发问题
并发案例
package com.jihu.Thread01;
//多个线程同时操作同一个对象
//买火车票的例子
//发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱
public class TestThread04 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) {
TestThread04 testThread04 = new TestThread04();
new Thread(testThread04,"小明").start();
new Thread(testThread04,"老师").start();
new Thread(testThread04,"张三").start();
}
}
输出结果
张三-->拿到了第8票
老师-->拿到了第9票
老师-->拿到了第6票
老师-->拿到了第5票
老师-->拿到了第4票
老师-->拿到了第3票
老师-->拿到了第2票
老师-->拿到了第1票
张三-->拿到了第3票
小明-->拿到了第10票
张三-->拿到了第7票
龟兔赛跑案例
package com.jihu.Thread01;
//模拟龟兔赛跑
public class Race implements Runnable {
//胜利者
private static String winner;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
//模拟兔子休息
if (Thread.currentThread().getName().equals("兔子") && i%10==0){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//判断比赛是否结束
Boolean flag = gameover(i);
//如果比较结束了,就停止程序
if (flag){
break;
}
System.out.println(Thread.currentThread().getName()+"-->跑了"+i+"步");
}
}
//判断是否完成比赛
public 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();
}
}
输出结果
乌龟-->跑了97步
乌龟-->跑了98步
乌龟-->跑了99步
winner is :乌龟
4.实现Callable接口(了解)
案例
package com.jihu.Demo02;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
//线程创建方式三: 实现callable接口
/*
callable的好处
1.可以定义返回值
2.可以抛出异常
*/
public class TestCallable implements Callable<Boolean> {
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) throws ExecutionException, InterruptedException {
TestCallable t1 = new TestCallable("https://148342yin-1316298725.cos.ap-beijing.myqcloud.com/images/blog/20220306175925.png","1.png");
TestCallable t2 = new TestCallable("https://148342yin-1316298725.cos.ap-beijing.myqcloud.com/images/blog/20220306175654.png","2.png");
TestCallable t3 = new TestCallable("https://148342yin-1316298725.cos.ap-beijing.myqcloud.com/images/blog/20220305194641.jpg","3.jpg");
//创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> r1 = (Future<Boolean>) ser.submit(t1);
Future<Boolean> r2= (Future<Boolean>) ser.submit(t2);
Future<Boolean> r3 = (Future<Boolean>) ser.submit(t3);
//获取结果
Boolean rs1 = r1.get();
Boolean rs2 = r2.get();
Boolean rs3 = r3.get();
System.out.println(rs1); //true
System.out.println(rs2); //true
System.out.println(rs3); //true
//关闭服务
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方法出现问题");
}
}
}
输出结果:
下载了文件名为:1.png
下载了文件名为:3.jpg
下载了文件名为:2.png
true
true
true
3.静态代理模式
婚庆公司的案例
package com.jihu.Demo02;
/*
静态代理模式总结:
真实对象和dialing对象都要实现同一个接口
代理对象要代理真实角色
*/
/* 好处:
代理对象可以做很多真实对象做不了的事情
真实对象专注做自己的事情
*/
public class StacticProxy {
public static void main(String[] args) {
//You you = new You();
//WeddingCompany weddingCompany = new WeddingCompany(you);
new Thread( ()-> System.out.println("我爱你")).start();
WeddingCompany weddingCompany = new WeddingCompany(new 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("结婚之前,布置现场");
}
}
输出结果:
我爱你
结婚之前,布置现场
老师我要结婚了,超开森
结婚之后,收尾款
4.Lamda表达式
案例1:
package com.jihu.lamda;
//推到lamda表达式
public class TestLamda {
//3.静态内部类
static class Like2 implements ILike{
@Override
public void lamda() {
System.out.println(" i like lamda2");
}
}
public static void main(String[] args) {
ILike like = new Like();
like.lamda();
Like2 like2 = new Like2();
like2.lamda();
//4.局部内部类
class Like3 implements ILike{
@Override
public void lamda() {
System.out.println(" i like lamda3");
}
}
Like3 like3 = new Like3();
like3.lamda();
//5.匿名内部类,没有类的名称,必须借助接口或者父类
like = new ILike() {
@Override
public void lamda() {
System.out.println(" i like lamda4");
}
};
like.lamda();
//6.用lamda简化
like =() ->{
System.out.println(" i like lamda5");
};
like.lamda();
}
}
//1.定义一个函数式接口
interface ILike{
void lamda();
}
//2.实现类
class Like implements ILike{
@Override
public void lamda() {
System.out.println(" i like lamda");
}
}
输出结果
i like lamda
i like lamda2
i like lamda3
i like lamda4
i like lamda5
案例2
package com.jihu.lamda;
/*总结
lamda表达式只能有一行代码的情况下才能简化成为一行,如果有多行,那么就用代码块包裹。
前提是接口为函数式接口
多个参数也可以去掉参数类型,要去掉就都去掉,必须加上括号
*/
public class TestLamda2 {
public static void main(String[] args) {
Ilove love = null;
/* class Love implements Ilove{
@Override
public void love(int a) {
System.out.println(" i love you "+a);
}
}*/
//1.lamda表示简化
/* love = (int a)-> {
System.out.println(" i love you "+a);
};*/
//.简化1. 参数类型
love = (a)->{
System.out.println(" i love you "+a);
};
//简化2. 简化括号
/* love = a->{
System.out.println(" i love you "+a);
System.out.println(" i love you -->too ");
};*/
//简化3. 去掉花括号
love = a -> System.out.println(" i love you "+a);
love.love(520);
/*总结
lamda表达式只能有一行代码的情况下才能简化成为一行,如果有多行,那么就用代码块包裹。
前提是接口为函数式接口
多个参数也可以去掉参数类型,要去掉就都去掉,必须加上括号
*/
}
}
interface Ilove{
void love(int a);
}
输出结果
i love you 520
案例3
package com.jihu.lamda;
public class TestLamda3 {
public static void main(String[] args) {
car car=(a,b,c)->System.out.println("购买的汽车"+a+b+c);
car.buychar(10,54,78);
}
}
interface car{
void buychar(int a,int b,int c);
}
输出结果:
购买的汽车105478
3.线程状态
线程状态概况:
1.线程停止
package com.jihu.state;
/* 测试 stop
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 testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main"+i);
//调用stop方法切换标志位,让线程停止
if (i==900){
testStop.stop();
System.out.println("线程该停止了");
}
}
}
}
输出结果:
main898
run ... Thread2338
main899
run ... Thread2339
main900
run ... Thread2340
run ... Thread2341
线程该停止了
main901
main902
main997
main998
main999
2.线程休眠_sleep
package com.jihu.state;
import com.jihu.Thread01.TestThread04;
import java.text.SimpleDateFormat;
import java.util.Date;
//模拟倒计时
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 (Exception exception) {
exception.printStackTrace();
}
}
}
//模拟倒计时
public static void tenDown() throws InterruptedException {
int num = 10;
while (true){
Thread.sleep(1000); //1000等于1毫秒
System.out.println(num--);
if (num<=0){
break;
}
}
}
}
输出结果:
23:27:41
23:27:42
23:27:43
23:27:44
23:27:45
23:27:46
23:27:47
3.线程礼让_yield
package com.jihu.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()+":start");
Thread.yield(); //礼让
System.out.println(Thread.currentThread().getName()+":end");
}
}
输出结果:
B:start
A:start
B:end
A:end
4.线程强制执行_join
join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞
可以想象为插队
package com.jihu.state;
//测试join方法 想象为插队
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; 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 < 300; i++) {
if (i==200){
thread.join(); //插队
}
System.out.println("main:"+i);
}
}
}
输出结果
线程vip来了996
线程vip来了997
线程vip来了998
线程vip来了999
main:200
main:201
main:202
main:203
main:204
main:205
5.观测线程状态
package com.jihu.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 (Thread.State.TERMINATED != state){
Thread.sleep(100);
state = thread.getState(); //更新线程状态
System.out.println(state); //输出状态
}
}
}
输出结果:
NEW
RUNNABLE
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
///////
TERMINATED
6.线程的优先级
package com.jihu.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();
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());
}
}
输出结果:
main--->5
Thread-3--->10
Thread-4--->8
Thread-5--->7
Thread-2--->4
Thread-0--->5
Thread-1--->1
7.守护线程(daemon)
package com.jihu.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() {
System.out.println("上帝一直保佑着你!");
}
}
//你
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 365; i++) {
System.out.println("你一生都开心的活着!");
}
System.out.println("============goodbye world!===============");
}
}
输出结果:
你一生都开心的活着!
你一生都开心的活着!
你一生都开心的活着!
你一生都开心的活着!
你一生都开心的活着!
你一生都开心的活着!
你一生都开心的活着!
你一生都开心的活着!
============goodbye world!===============
上帝一直保佑着你!
4.线程同步(重点)
1.三大不安全案例
案例1
package com.jihu.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(1000);
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
输出结果
牛逼的你们拿到9
可恶的黄牛党拿到10
苦逼的我拿到8
苦逼的我拿到7
可恶的黄牛党拿到6
牛逼的你们拿到5
可恶的黄牛党拿到3
苦逼的我拿到2
牛逼的你们拿到4
牛逼的你们拿到0
可恶的黄牛党拿到1
苦逼的我拿到-1
案例2
package com.jihu.syn;
//不安全的取钱
//两个人去银行取钱, 账户
public class UnSafeBank {
public static void main(String[] args) {
//账户
Acount acount = new Acount(100,"结婚基金");
Bank you = new Bank(acount,50,"你");
Bank youwife = new Bank(acount,100,"你妻子");
you.start();
youwife.start();
}
}
//账户
class Acount{
int money; //余额
String name; //卡名
public Acount(int money, String name) {
this.money = money;
this.name = name;
}
}
//银行:模拟取款
class Bank extends Thread{
Acount acount; //账户
//取了多少钱
int drawingMoney;
//现在手里有多少钱
int nowMoney;
public Bank(Acount acount,int drawingMoney,String name){
super(name);
this.acount = acount;
this.drawingMoney = drawingMoney;
}
//取钱
@Override
public void run() {
//判断有没有钱
if (acount.money - drawingMoney <0){
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
}
//sleep可以放大问题的发生性
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额 = 余额-你取的钱
acount.money = acount.money - drawingMoney;
//你手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(acount.name + "余额为:"+acount.money);
//Thread.currentThread().getName() == this.getName()
System.out.println(this.getName() + "手里的钱:"+nowMoney);
}
}
输出结果:
结婚基金余额为:50
你手里的钱:50
你妻子钱不够,取不了
案例3
package com.jihu.syn;
import java.util.ArrayList;
import java.util.List;
//线程不安全的集合
public class UnSafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 1000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
System.out.println(list.size());
}
}
输出结果:
996
2.同步方法及同步块
把前面三个案例改为同步
案例一
//synchronized 同步方法,锁的是this
private synchronized void buy() throws InterruptedException {
//判断是否有票
if (ticketNums <= 0){
flag = false;
return;
}
//模拟延迟
Thread.sleep(1000);
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
案例二
//取钱
//synchronized 默认锁的是this
@Override
public void run() {
//同步块
//锁的对象就是变化的量, 需要增删改的对象
synchronized (acount){
//判断有没有钱
if (acount.money - drawingMoney <0){
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
return;
}
//sleep可以放大问题的发生性
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额 = 余额-你取的钱
acount.money = acount.money - drawingMoney;
//你手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(acount.name + "余额为:"+acount.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<>();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 1000; i++) {
new Thread(()->{
//synchronized 锁住list
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
System.out.println(list.size());
}
}
3.JUC安全类型的集合 (CopyOnWriteArrayList)
package com.jihu.syn;
import java.util.concurrent.CopyOnWriteArrayList;
//测试JUC安全类型的集合
public class TestJUC {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
for (int i = 0; i < 1000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
输出结果:
1000
4.死锁
package com.jihu.Thread05;
//死锁: 多个线程互相抱着对方需要的资源,然后形成僵持
public class DeadLock {
public static void main(String[] args) {
Makeup makeup = new Makeup(0,"灰姑娘");
Makeup makeup2 = new Makeup(1,"白雪公主");
makeup.start();
makeup2.start();
}
}
//口红
class Lipstick{
}
//镜子
class Mirror{
}
class Makeup extends Thread{
//需要的资源只有一份,用static来保证只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice; //选择
String girlName; //使用化妆品的人
public 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) { //1秒中后获得镜子的锁
System.out.println(this.girlName + "获得镜子的锁");
}
}
}else {
synchronized (mirror) { //获得镜子的锁
System.out.println(this.girlName + "获得镜子的锁");
Thread.sleep(2000);
synchronized (lipstick) { //2秒中后获得口红的锁
System.out.println(this.girlName + "获得口红的锁");
}
}
}
}
}
输出结果: //会发生死锁
灰姑娘获得口红的锁
白雪公主获得镜子的锁
//这样会解除死锁
//化妆,互相持有对方的锁,就是需要拿到对方的资源
private void makeup() throws InterruptedException {
if (choice == 0) {
synchronized (lipstick) { //获得口红的锁
System.out.println(this.girlName + "获得口红的锁");
Thread.sleep(1000);
}
synchronized (mirror) { //1秒中后获得镜子的锁 ////这样会解除死锁
System.out.println(this.girlName + "获得镜子的锁");
}
}else {
synchronized (mirror) { //获得镜子的锁
System.out.println(this.girlName + "获得镜子的锁");
Thread.sleep(2000);
}
synchronized (lipstick) { //2秒中后获得口红的锁
System.out.println(this.girlName + "获得口红的锁");
}
}
}
输出结果: ////这样会解除死锁
灰姑娘获得口红的锁
白雪公主获得镜子的锁
白雪公主获得口红的锁
灰姑娘获得镜子的锁
5.Lock锁
package com.jihu.Thread05;
import java.util.concurrent.locks.ReentrantLock;
public class TestLock {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket,"a").start();
new Thread(buyTicket,"c").start();
new Thread(buyTicket,"b").start();
}
}
class BuyTicket implements Runnable{
int TicketNums = 10;
//定义lock锁
private 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(Thread.currentThread().getName()+"获得了"+ TicketNums--+"票");
}else{
break;
}
} finally {
lock.unlock(); //解锁
}
}
}
}
输出结果
a获得了10票
a获得了9票
c获得了8票
b获得了7票
a获得了6票
a获得了5票
c获得了4票
b获得了3票
a获得了2票
a获得了1票
6.synchronized与lock的对比
5.线程协作
1.生产者消费者问题
2.解决方式1 -->管程法
package com.jihu.gaoji;
//测试: 生产者消费者模型 -> 利用缓冲区解决: 管程法
//生产者 , 消费者 , 产品, 缓冲区
public class TestPC {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Productor(container).start();
new Customer(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 Customer extends Thread{
SynContainer container;
public Customer(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;
//可以通知消费者消费了
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;
}
}
输出结果
消费了-->75只鸡
生产了76只鸡
消费了-->76只鸡
生产了77只鸡
消费了-->77只鸡
生产了78只鸡
消费了-->78只鸡
生产了79只鸡
消费了-->79只鸡
生产了80只鸡
消费了-->80只鸡
3.解决方式2 -->信号灯法
package com.jihu.gaoji;
//测试生产者消费者问题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{
//演员表演,观众等待 T
//观众观看,演员等待 F
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;
}
}
输出结果:
演员表演了:快乐大本营播放中
观看了:快乐大本营播放中
演员表演了:抖音:记录美好生活
观看了:抖音:记录美好生活
演员表演了:快乐大本营播放中
观看了:快乐大本营播放中
演员表演了:抖音:记录美好生活
观看了:抖音:记录美好生活
演员表演了:快乐大本营播放中
观看了:快乐大本营播放中
4.线程池
package com.jihu.gaoji;
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.shutdownNow();
}
}
class MyThread implements Runnable{
@Override
public void run() {
/* for (int i = 0; i < 2; i++) {
System.out.println(Thread.currentThread().getName()+i);
}*/
System.out.println(Thread.currentThread().getName());
}
}
输出结果:
pool-1-thread-1
pool-1-thread-4
pool-1-thread-2
pool-1-thread-3
5.总结
package com.jihu.gaoji;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Demo03 {
public static void main(String[] args) {
/*MyThread1 myThread = new MyThread1();
myThread.start();*/
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 e) {
e.printStackTrace();
} catch (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.实现Runnable接口
class MyThread3 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("MyThread3");
return 100;
}
}
输出结果:
MyThread1
MyThread2
MyThread3
100
收藏
关注
评论