java2_day08之多线程
目录
-
线程简介
-
线程实现(重点)
-
线程状态
-
线程同步(重点)
-
-
高级主题
第二个的更加详细。
2 线程实现
继承Thread类
-
调用start()开启线程是交替执行的,因为我们的电脑是单核的,只有一个CPU,如果是多核的,则是并行。但是如果主线程此时调用run方法,则是先执行run,再执行后面的语句。
-
总结:线程开启不一定立即执行,由cpu进行调度。比如调用start()的时候,会先执行主线程里边的语句,然后等cpu调度过来,才开始执行run里边的。
-
只有一个cpu,多线程是并发执行的,所以最后执行完成的顺序是随机的,每次可能都不一样。
实现类Runnable接口
发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱。
龟兔赛跑
lambda表达式:
public class Demo13_Lamda4 {
public static void main(String[] args) {
//6.lamda简化
ILike like = () ->{
System.out.println("I like lamda4");
}; // 实现类,或者说新建对象
like.lamda();
}
}
public class Demo14_LamdaCase2 {
public static void main(String[] args) {
// 1.lamda
ILove love = (int a) -> {
System.out.println("I love you -->" + a);
};
// 2.lamda简化1.0
love = (a) -> {
System.out.println("I love you -->" + a);
};
// 3.lamda简化2.0
love = a -> {
System.out.println("I love you -->" + a);
};
// 3.lamda简化3.0
love = a -> System.out.println("I love you -->" + a);
/**总结:
* {}简略的条件是只能有一行代码,多行{}就不能简略了
* 前提是接口为函数式接口(只能有一个方法)
* 多个参数也可以去掉参数类型,要去掉就都去掉,必须加上()
* 也是实现接口了的,只是通过lambda的方式简化了
*/
love.love(520);
}
}
interface ILove {
void love(int a);
}
3 线程状态
3.1 线程停止
/**
* 测试stop
* 1.建议线程正常停止-->利用次数,不建议死循环
* 2.建议使用标志位-->设置一个标志位
* 3.不要使用stop或者destroy等过时或者JDK不建议使用的方法
*/
public class Demo15_StopThread implements Runnable {
// 1. 设置一个标志位
private boolean flag = true;
3.2 线程休眠
/**
* 模拟网络延迟:放大问题的发生性
*/
public class Demo16_SleepThread implements Runnable {
//票数
private int ticketNums = 10;
/**
* 模拟倒计时
*/
public class Demo17_SleepThread2 {
public static void main(String[] args) {
try {
tenDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//模拟倒计时
public static void tenDown() throws InterruptedException {
int num = 10;//10秒
while (true) {
Thread.sleep(1000); //休眠
System.out.println(num--);
if (num <= 0) {
break;
}
}
}
}
/**
* 每一秒获取当前时间
*/
public class Demo18_SleepThread3 {
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();
}
}
}
}
3.3 线程礼让
-
礼让线程,让当前正在执行的线程暂停,但是不阻塞
-
将线程从运行状态转为就绪状态
-
让cpu重新调度,礼让不一定成功!看CPU心情(其实就是出来同时竞争)
/**
* 测试礼让线程
* 礼让不一定成功,看cpu心情
*/
public class Demo19_YieldThread {
public static void main(String[] args) {
MyYeild myYeild = new MyYeild();
new Thread(myYeild, "a").start();
new Thread(myYeild, "b").start();
}
}
class MyYeild implements Runnable {
3.4 join
-
join合并线程,待此线程执行完成后,在执行其他线程,其他线程阻塞。
-
可以想象成插队
/**
* 测试join
* 插队
*/
public class Demo20_JoinThread implements Runnable {
3.5 线程状态观测
/**
* 观察测试线程状态
*/
public class Demo21_ThreadState {
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);
//观察启动后
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);
}
//死亡后的线程不能再启动了,启动会报异常
//thread.start();
}
}
3.6 线程优先级
/**
* 线程优先级
*/
public class Demo22_ThreadPriority{
public static void main(String[] args) {
//主线程默认优先级
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread thread1 = new Thread(myPriority);
Thread thread2 = new Thread(myPriority);
Thread thread3 = new Thread(myPriority);
Thread thread4 = new Thread(myPriority);
Thread thread5 = new Thread(myPriority);
//先设置优先级,再启动
thread1.start();
thread2.setPriority(1);
thread2.start();
thread3.setPriority(4);
thread3.start();
thread4.setPriority(Thread.MAX_PRIORITY);//MAX_PRIORITY=10
thread4.start();
thread5.setPriority(8);
thread5.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
3.7 守护线程
-
线程分为用户线程和守护线程
-
虚拟机必须确保用户线程执行完毕
-
虚拟机不能等待守护线程执行完毕
-
如,后台记录操作日志,监控内存,垃圾回收等待
/**
* 测试守护线程
* 上帝守护你
*/
public class Demo23_DaemonThread {
public static void main(String[] args) {
God god = new God();
You you = new You();
Thread thread = new Thread(god);
//默认false表示是用户线程,正常的线程都是用户线程...
thread.setDaemon(true);
//上帝守护线程启动
thread.start();
//你 用户线程启动
new Thread(you).start();
}
}
//上帝
class God implements Runnable{
@Override
public void run() {
while (true){
System.out.println("上帝保佑着你");
}
}
}
//你
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("你一生都开心的活着");
}
System.out.println("====goodbye!world====");
}
}
-
你死了之后上帝还要跑一会,因为虚拟机停止需要时间
4 线程同步
-
多个线程操作同一个资源
-
并发:同一个对象被多个对象同时操作,这与小林说的有所区别
-
天然解决办法:排队,一个个来
4.1 队列和锁
安全形成条件: 队列+锁
//不安全买票
public class Demo24_UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket, "张三").start();
new Thread(buyTicket, "李四").start();
new Thread(buyTicket, "王五").start();
}
}
class BuyTicket implements Runnable {
//票
private int ticketNums = 10;
boolean flag = true;
@Override
public void run() {
//买票
while (flag) {
try {
buy();
} catch (Exception e) {
e.printStackTrace();
}
}
}
//买票
private void buy() {
//判断是否有票
if (ticketNums <= 0) {
flag = false;
return;
}
//延迟
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
//买票
System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
}
}
/**
* 不安全的取钱
*/
public class Demo25_UnsafeBank {
public static void main(String[] args) {
Account account = new Account(100, "结婚基金");
Drawing you = new Drawing(account, 50, "展堂");
Drawing girlfriend = new Drawing(account, 100, "sad");
you.start();
girlfriend.start();
}
}
//账户
class Account {
int money;//余额
String cardName;//卡名
public Account(int money, String cardName) {
this.money = money;
this.cardName = cardName;
}
}
//银行:模拟取款
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;
}
try {
Thread.sleep(1000);//sleep可以放大问题的发生性
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内金额 = 余额-你的钱
account.money = account.money - drawingMoney;
//你手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.cardName + "余额为:" + account.money);
//this.getName()==Thread.currentThread().getName()
System.out.println(this.getName() + "手里的钱:" + nowMoney);
}
}
4.2 同步方法
锁的对象应该是变化的量,需要增删改的对象。
/**
* 安全的取钱 同步块
*/
public class Demo28_SafeBank {
public static void main(String[] args) {
Account1 account = new Account1(100, "结婚基金");
Drawing1 you = new Drawing1(account, 50, "展堂");
Drawing1 girlfriend = new Drawing1(account, 100, "sad");
you.start();
girlfriend.start();
}
}
//账户
class Account1 {
int money;//余额
String cardName;//卡名
public Account1(int money, String cardName) {
this.money = money;
this.cardName = cardName;
}
}
//银行:模拟取款
class Drawing1 extends Thread {
Account1 account;//账户
int drawingMoney;//取金额
int nowMoney;//你手里的钱
public Drawing1(Account1 account, int drawingMoney, String name) {
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
//取钱
@Override
public void run() {
//锁的对象就是变量的量,需要增删改查的对象
synchronized (account) {
//判断是否有钱
if (account.money - drawingMoney < 0) {
System.out.println(Thread.currentThread().getName() + "余额不足,不能进行取钱");
return;
}
try {
Thread.sleep(1000);//放大问题的发生性
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内金额 = 余额-你的钱
account.money = account.money - drawingMoney;
//你手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.cardName + "余额为:" + account.money);
//this.getName()==Thread.currentThread().getName()
System.out.println(this.getName() + "手里的钱:" + nowMoney);
}
}
//测试JUC安全类型的集合
public class Demo30_ThreadJuc {
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());
}
}
4.3 死锁
-
多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形。某一个同步块同时拥有“两个以上对象的锁”时,就会发生死锁的问题。
/**
* 死锁:多个线程互相抱着对方需要的资源,然后形成僵持
* 解决:一个锁只锁一个对象
*/
class Demo31_DeadLock {
public static void main(String[] args) {
Makeup makeup = new Makeup(0, "灰姑娘");
Makeup makeup1 = new Makeup(1, "白雪公主");
makeup.start();
makeup1.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) {//一秒钟后想获得镜子
System.out.println(this.girlName + "获得镜子的锁");
}
}
} else {
synchronized (mirror) {//获得镜子的锁
System.out.println(this.girlName + "获得镜子的锁");
Thread.sleep(2000);
synchronized (lipstick) {//二秒钟后想获得的锁
System.out.println(this.girlName + "获得口红的锁");
// 把这里的锁拿到外边去应该就可以了
}
}
}
}
}
-
只要一个人不同时拿两把锁就好了
4.4 Lock锁
ReentrantLock,可重入锁。
//测试Lock锁
public class Demo32_ThreadLock {
public static void main(String[] args) {
TestLock testLock = new TestLock();
new Thread(testLock).start();
new Thread(testLock).start();
new Thread(testLock).start();
}
}
class TestLock implements Runnable {
int tickerNums = 10;
//定义Lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
//加锁
try {
lock.lock();
if (tickerNums <= 0) {
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(tickerNums--);
} catch (Exception e) {
e.printStackTrace();
} finally {
//解锁
lock.unlock();
}
}
}
}
5 线程通信问题
5.1 线程协作
生产者消费者模式
synchronized可以实现同步,但是不能实现不同线程之间的通信。
解决方式1:建立一个缓冲区
/**
* 测试:生产者消费者模型-->利用缓冲区解决:管程法
*/
public class Demo33_ThreadPC {
public static void main(String[] args) {
SynContainer synContainer = new SynContainer();
new Producer(synContainer).start();
new Consumer(synContainer).start();
}
}
//生产者
class Producer extends Thread { // 继承了Thread,可以实现线程。
//容缓冲区
SynContainer container;
public Producer(SynContainer container) {
this.container = container;
}
//生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Product(i));
System.out.println("生产了" + i + "件产品");
}
}
}
//消费者
class Consumer extends Thread { // 继承了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的话,假如消费者1消费了最后一个,这是index变成0此时释放锁被消费者2拿到而不是生产者拿到,这时消费者的wait是在if里所以它就直接去消费index-1下标越界,如果是while就会再去判断一下index得值是不是变成0了*/
while (count == products.length) {
//通知消费者消费,等待生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满,需要丢入产品
products[count] = product;
count++;
//通知消费者消费
this.notifyAll();
}
//消费者消费产品
public synchronized Product pop() {
//判断是否能消费
while (count <= 0) {
//等待生产者生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费
count--;
Product product = products[count];
//吃完了 通知生产者生产
this.notifyAll();
return product;
}
}
解决方式2:创建一个标志位,0或者1做相应的动作
从下边的代码中可以看出,这种方式就是表演一个看一个,不会存储更多,和带缓冲区的不一样。
package com.kuang.thread.Producer_Consumer;
//测试生产者消费者问题2:信号灯法,标志位解决
public class TestPC02 {
public static void main(String[] args) {
TV tv = new TV();
new Player (tv).start();
new Watcher (tv) .start();
}
}
//生产者-->演员
class Player extends Thread { // 继承了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 { // 继承了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 extends Thread {
//演员表演,观众等待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;
}
}
6 使用线程池
//测试线程池
public class Demo35_ThreadPool {
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());
service.execute(new MyThread());
service.execute(new MyThread());
//关闭连接
service.shutdown();
}
}
class MyThread implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
7 总结
本文来自博客园,作者:{诺不克},转载请注明原文链接:https://www.cnblogs.com/xinxueqi/p/16334843.html
好好写代码,天天开心啊!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!