1.核心概念
- 线程就是独立的执行路径
- 在程序运行时,即使没有自己创建线程,后台也会有多个线程,如主线程,gc线程。
- main()称之为主线程,为系统的入口,用于执行整个程序;
- 在一个进程中,如果开辟了多个线程,线程的运行由调度器安排调度,调度器是与操作系统紧密相关的,先后顺序是不能人为干预的。
- 对同一份资源操作时,会存在资源抢夺的问题,需要家人并发控制;
- 线程会带来额外的开销,如cpu调度时间,并发控制开销
- 每个线程在自己工作内存交互,存在控制不当会造成数据不一致
- 线程不一定立即执行,统一听从CPU调度
2.创建线程
1.继承Thread类
- 自定义线程类继承
Thread
类
- 重写run()方法,编写线程执行提
- 创建线程对象,调用start()方法启动线程
代码如下
| package com.sanduo.annotation; |
| |
| |
| |
| public class TestThread1 extends Thread{ |
| @Override |
| public void run() { |
| |
| for (int i = 0; i < 20; i++) { |
| System.out.println("我在上厕所"); |
| } |
| } |
| |
| public static void main(String[] args) { |
| |
| |
| |
| |
| TestThread1 testThread1 = new TestThread1(); |
| |
| testThread1.start(); |
| for (int i = 0; i < 20; i++) { |
| System.out.println("我在吃饭"); |
| } |
| } |
| } |
| |
案例:多线程下载图片
1.导入conmmons-io 包
2.代码分析
| package com.sanduo.annotation; |
| |
| import org.apache.commons.io.FileUtils; |
| |
| import java.io.File; |
| import java.io.IOException; |
| import java.net.URL; |
| |
| |
| 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://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic_source%2Fb0%2Fd1%2Ff3%2Fb0d1f35504e4106d48c84434f2298ada.jpg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1674289486&t=7147879625e28333af357eb58b8ff16d","美女图片1.jpg"); |
| TestThread2 t2 = new TestThread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic%2F75%2Fdc%2F50%2F75dc50577d3d3d2bd5fd8db728e7bf77.jpg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1674289542&t=703f01845ca443eab8b513921a0b0c8d","美女图片2.jpg"); |
| TestThread2 t3 = new TestThread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.win4000.com%2Fm00%2F12%2Feb%2Fa03225e61dbb2f3207c011718b21b6e1.jpg&refer=http%3A%2F%2Fpic1.win4000.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1674289591&t=fae37f917659cc3a2b35418709c0fa05","美女图片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异常"); |
| } |
| } |
| } |
2.实现Runnable接口
- 定义一个类实现Runnable接口
- 实现run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程
代码如下
| package com.sanduo.annotation; |
| |
| |
| public class TestThread3 implements Runnable { |
| @Override |
| public void run() { |
| for (int i = 0; i < 20; i++) { |
| System.out.println("我在吃饭"+i); |
| } |
| } |
| public static void main(String[] args) { |
| |
| TestThread3 runnable = new TestThread3(); |
| |
| |
| |
| new Thread(runnable).start(); |
| for (int i = 0; i < 200; i++) { |
| System.out.println("我在一边吃饭,一边玩手机哈哈哈哈~~"+i); |
| } |
| } |
| } |
3.继承Thread类与实现Runnable接口比较
- 继承Thread类
- 子类继承Thread类具备多线程能力
- 启动线程:子类对象.start()
- 不建议使用:避免OOP单继承的局限性
- 实现Runnable接口
- 实现接口Runnable具有多线程能力
- 启动线程:传入目标对象+Thread对象.start()
- 推荐使用:避免单继承局限性,灵活方便,方便一个对象被多个线程使用
4.初识并发
多个线程同事操作一个对象 举例:买火车票,保证不会超卖,使用多线程时发现一个问题多线程操作同一资源的情况,线程不安全,数据紊乱
| package com.sanduo.annotation; |
| |
| |
| public class TestThread4 implements Runnable { |
| private int ticketNum = 20; |
| @Override |
| public void run() { |
| while (true){ |
| if(ticketNum<=0) break; |
| System.out.println(Thread.currentThread().getName()+"-->抢到了第"+ticketNum--+"张票"); |
| } |
| try { |
| Thread.sleep(200); |
| } catch (InterruptedException e) { |
| e.printStackTrace(); |
| } |
| } |
| public static void main(String[] args) { |
| TestThread4 ticket = new TestThread4(); |
| new Thread(ticket,"小明").start(); |
| new Thread(ticket,"小王").start(); |
| new Thread(ticket,"黄牛党").start(); |
| } |
| } |
| |
案例:龟兔赛跑
| package com.sanduo.annotation; |
| |
| public class Race implements Runnable { |
| |
| private static String winner = null; |
| |
| @Override |
| public void run() { |
| for (int i = 0; i <= 100; i++) { |
| if(Thread.currentThread().getName()=="兔子" && i%10==0){ |
| try { |
| Thread.sleep(1); |
| } 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; |
| } else { |
| 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(); |
| } |
| } |
5.实现Callable接口
- 实现Callable接口,需要返回值类型
- 重写call方法,需要抛出异常
- 创建目标对象
- 创建服务执行:ExecutoService ser = Executors.newFixedThreadPool(1)
- 提交执行:Future result1=ser.submit(1)
- 获取结果:boolean r1 = result1.get();
- 关闭服务:ser.shutdownNow();
代码实现如下:
| package com.sanduo.annotation.demo02; |
| import org.apache.commons.io.FileUtils; |
| import java.io.File; |
| import java.io.IOException; |
| import java.net.URL; |
| import java.util.concurrent.*; |
| |
| |
| |
| |
| public class myCallable implements Callable<Boolean> { |
| private String url; |
| private String name; |
| |
| public myCallable(String url, String name) { |
| this.url = url; |
| this.name = name; |
| } |
| @Override |
| public Boolean call() throws Exception { |
| WebDownloader webDownloader = new WebDownloader(); |
| webDownloader.downloader(url, name); |
| System.out.println("下载文件名为:" + name); |
| return true; |
| } |
| |
| public static void main(String[] args) throws ExecutionException, InterruptedException { |
| myCallable t1 = new myCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic_source%2Fb0%2Fd1%2Ff3%2Fb0d1f35504e4106d48c84434f2298ada.jpg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1674289486&t=7147879625e28333af357eb58b8ff16d", "美女图片1.jpg"); |
| myCallable t2 = new myCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic%2F75%2Fdc%2F50%2F75dc50577d3d3d2bd5fd8db728e7bf77.jpg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1674289542&t=703f01845ca443eab8b513921a0b0c8d", "美女图片2.jpg"); |
| myCallable t3 = new myCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.win4000.com%2Fm00%2F12%2Feb%2Fa03225e61dbb2f3207c011718b21b6e1.jpg&refer=http%3A%2F%2Fpic1.win4000.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1674289591&t=fae37f917659cc3a2b35418709c0fa05", "美女图片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(); |
| |
| 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异常"); |
| } |
| } |
| } |
6.静态代理
静态代理模式总结:
- 真实对象和代理对象都要实现同一个接口
- 代理对象要代理真实角色
好处
- 代理对象可以做很多真实对象做不了的事情
- 真实对象专注做自己的事情
案例:结婚
代码如下
| package com.sanduo.annotation.demo03; |
| |
| |
| |
| |
| |
| |
| public class StaticProxy { |
| public static void main(String[] args) { |
| |
| |
| |
| new Thread(()-> System.out.println("11111")).start(); |
| new WeddingCompany(new You()).HappyMarry(); |
| } |
| } |
| interface Marry{ |
| void HappyMarry(); |
| } |
| |
| class You implements Marry{ |
| @Override |
| public void HappyMarry() { |
| System.out.println("有些人20岁就死了,80岁才埋~~~~~"); |
| } |
| } |
| |
| 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("结婚之后,收尾款"); |
| } |
| } |
7.Lamda表达式
为什么要使用Lambda表达式
- 避免匿名内部类定义过多
- 可以让你的代码看起来很简洁
- 去掉一堆没有意义的代码,只留下核心
总结
- lambda表达式只能有一行代码的情况下才能简化成一行,如果有多行,那么就用代码块包裹
- 前提是接口为函数式接口
- 多个参数也可以去掉参数类型,要去掉都去掉,必须加括号
代码示例
| package com.sanduo.annotation.demo03.lambda; |
| |
| public class TestLambda2 { |
| public static void main(String[] args) { |
| ILove love = (int a)->{ |
| System.out.println("i love you ->" + a); |
| }; |
| |
| love = (a)->{ |
| System.out.println("i love you ->" + a); |
| }; |
| |
| love = a -> { |
| System.out.println("i love you ->" + a); |
| }; |
| |
| love = a -> System.out.println("i love you ->" + a); |
| love.love(522); |
| } |
| } |
| |
| interface ILove{ |
| void love(int a); |
| } |
| |
| class Love implements ILove{ |
| @Override |
| public void love(int a) { |
| System.out.println("i love you ->" + a); |
| } |
| } |
| |
3.线程状态

1.线程停止
- 建议线程正常停止-->利用次数,不建议死循环
- 建议使用标志位-->设置一个标志位
- 不要使用stop()或者destroy()等过时的方法或者JDK不建议的方法
代码示例
| package com.sanduo.annotation.demo03.state; |
| |
| |
| |
| |
| |
| public class TestStop implements Runnable{ |
| |
| private boolean flag = true; |
| @Override |
| public void run() { |
| int i = 0; |
| while (flag){ |
| System.out.println("run.....Thread" + 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){ |
| |
| testStop.stop(); |
| System.out.println("线程停止了"); |
| } |
| } |
| } |
| } |
2.线程休眠_sleep
- sleep(时间)指定当前线程阻塞的毫秒数
- sleep存在异常InterruptedExecption;
- sleep时间到达后线程进入就绪状态;
- sleep可以模拟网络延时,倒计时等;
- 每一个对象都有一个锁,sleep不会释放锁
代码示例
| package com.sanduo.annotation.demo03.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("yyyy-MM-dd 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; |
| } |
| } |
| } |
| } |
3.线程礼让_yield
- 礼让线程,让当前正在执行的线程暂停,但不阻塞
- 将线程从运行状态转为就绪状态
- 让cpu重新调度,礼让不一定成功!看CPU心情
代码示例
| package com.sanduo.annotation.demo03.state; |
| |
| 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.线程强制执行
- Join合并线程,待此线程执行完成后,在执行其他线程,其他线程阻塞
- Join会阻塞其他线程
| package com.sanduo.annotation.demo03.state; |
| public class TextJoin 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 { |
| TextJoin textJoin = new TextJoin(); |
| Thread thread = new Thread(textJoin); |
| thread.start(); |
| |
| for (int i = 0; i < 500; i++) { |
| if (i == 200) thread.join(); |
| System.out.println("main" + i); |
| } |
| } |
| } |
5.线程状态
线程有6种状态
- NEW
- RUNNABLE
- BLOCKED
- WAITING
- TIMED_WAITING
- TERMINATED
| package com.sanduo.annotation.demo03.state; |
| public class TestState { |
| public static void main(String[] args) { |
| 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); |
| while (state != Thread.State.TERMINATED){ |
| try { |
| Thread.sleep(100); |
| state = thread.getState(); |
| System.out.println(state); |
| } catch (InterruptedException e) { |
| e.printStackTrace(); |
| } |
| } |
| } |
| } |
6.线程的优先级
- Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度那个线程来执行。
- 线程的优先级用数字表示,范围从1~10
- Thread.MIN_PRIORITY = 1
- Thread.MAX_PRIORITY =10
- Thread.NORM_PRIORITY =5;
- 使用以下方式改变或获取优先级
- getPriority().setPriority(int xxx)
注意点:优先级低只是获得调度的概率低,并不优先级低就不会被调度了.这都是看CPU的调度
代码示例
| package com.sanduo.annotation.demo03.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); |
| t1.start(); |
| t2.setPriority(1); |
| t2.start(); |
| t3.setPriority(4); |
| t3.start(); |
| t4.setPriority(Thread.MAX_PRIORITY); |
| t4.start(); |
| t5.setPriority(8); |
| t5.start(); |
| } |
| } |
| class MyPriority implements Runnable{ |
| @Override |
| public void run() { |
| System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority()); |
| } |
| } |
7.线程守护
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕
- 虚拟机不用等待守护线程执行完毕
- 如,后台操作日志记录,监控内存,垃圾回收等待.
- setDaemon(true) ,默认是false表示用户线程,正常的线程都是用户线程
代码示例
| package com.sanduo.annotation.demo03.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); |
| 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.线程同步机制
发生在多个线程操作同一个资源
- 并发:同一个对象被多个线程同时操作
- 处理多线程问题时,多个线程访问同一个对象,并且某些线程还想修改对象。这个时候就需要线程同步。线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程在使用
- 由于同一进程的多个线程共享一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入 锁机制synchronized,当一个线程获得对象的排他锁,独占资源,其他线程必须等待,使用后释放即可。存在以下问题:
- 一个线程持有锁会导致其他所有需要此锁的线程挂起
- 在多线程竞争下,枷锁,释放锁会导致比较多的上下文切换 和 调度延时,引发性能问题;
- 如果一个优先级高的线程等待一个优先级低的线程释放锁 会导致优先级倒置,引起性能问题.
1.三个不安全的案例
1.不安全买票
| package com.sanduo.annotation.demo03.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(200); |
| |
| System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--); |
| } |
| } |
2.不安全取钱
| package com.sanduo.annotation.demo03.syn; |
| |
| |
| 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, "老婆"); |
| 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; |
| } |
| |
| try { |
| Thread.sleep(1000); |
| } catch (InterruptedException e) { |
| e.printStackTrace(); |
| } |
| |
| account.money = account.money - drawingMoney; |
| |
| nowMoney = nowMoney + drawingMoney; |
| System.out.println(account.name + "余额为:" + account.money); |
| |
| System.out.println(this.getName() + "手里的钱:" + nowMoney); |
| } |
| } |
3.不安全线程
| package com.sanduo.annotation.demo03.syn; |
| import java.util.ArrayList; |
| import java.util.List; |
| |
| public class UnsafeList { |
| public static void main(String[] args) { |
| List<String> list = new ArrayList<>(); |
| 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()); |
| } |
| } |
2.同步方法以及同步块
1.同步方法
- 由于我们可以通过
private
关键字来保证数据对象只能被方法访问,所有我们只需要针对方法提出一套机制,这套机制就是synchronized
关键字,他包括两种用法:synchronized
方法和synchronized
块.
| |
| public synchronized void method(int args){} |
synchronized
方法控制“对象”的访问,每个对象对应一把锁,每个synchronized
方法都必须获得调用该方法的锁才能执行,否则线程会阻塞,方法一旦执行,就独占锁,知道方法返回才释放,后面被阻塞的线程才能获得这个锁,继续执行
2.同步块
- 同步块:synchronized(Obj){}
- Obj称之为同步监视器
- Obj可以是任何对象,但是推荐使用共享资源作为同步监视器
- 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者是class
- 同步监视器的执行过程
- 第一个线程访问,锁定同步监视器,执行其中代码
- 第一个线程访问,发现同步监视器被锁定,无法访问
- 第一个线程访问完毕,解锁同步监视器
- 第二个线程访问,发现同步监视器没有锁,然后锁定并访问
3 案例优化
买车票
| package com.sanduo.annotation.demo03.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 synchronized void buy() throws InterruptedException { |
| |
| if(ticketNums<=0){ |
| flag = false; |
| return; |
| } |
| |
| Thread.sleep(200); |
| |
| System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--); |
| } |
| } |
银行取钱
| package com.sanduo.annotation.demo03.syn; |
| |
| |
| 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, "老婆"); |
| 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() { |
| |
| 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.name + "余额为:" + account.money); |
| |
| System.out.println(this.getName() + "手里的钱:" + nowMoney); |
| } |
| } |
| } |
安全线程
| package com.sanduo.annotation.demo03.syn; |
| |
| import java.util.ArrayList; |
| import java.util.List; |
| |
| |
| public class UnsafeList { |
| public static void main(String[] args) { |
| List<String> list = new ArrayList<>(); |
| 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()); |
| } |
| } |
3.死锁
- 多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形.某一个同步块同时拥有两个以上对象的锁时,就可能会发生死锁的问题
- 多个线程互相抱着对方需要的资源,然后形成僵持
死锁的避免方法
- 产生死锁的四个必要条件
- 互斥条件:一个资源每次只能被一个进程使用。
- 请求与保持条件:一个进程因请求资源而阻塞时,对已获得资源保持不放。
- 不剥夺条件:进程已获得的资源,在未使用完成之前,不能强行剥夺。
- 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
- 只要想办法破环其中任意一个或多个条件就可以避免死锁发生
代码示例
| package com.sanduo.annotation.demo03.syn; |
| public class DeadLock { |
| public static void main(String[] args) { |
| new Makeup(0,"灰姑娘").start(); |
| new Makeup(0,"白雪公主").start(); |
| } |
| } |
| class Lipstick{} |
| class Mirror{} |
| class Makeup extends Thread{ |
| |
| 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+"获得了镜子的锁"); |
| Thread.sleep(1000); |
| } |
| }else{ |
| synchronized (mirror){ |
| System.out.println(this.girlName+"获得了镜子的锁"); |
| Thread.sleep(2000); |
| } |
| synchronized (lipstick){ |
| System.out.println(this.girlName+"获得了口红的锁"); |
| } |
| } |
| } |
| } |
4.lock锁
- 从JDK5.0开始,Java提供了更强大的线程同步机制——通过显式定义锁对象来说实现同步。同步锁使用Lock对象充当。
java.util.concurrent.locks.Lock
接口式控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个对象对Lock对象枷锁,线程开始访问共享资源之前应先获得Lock对象
ReentrantLock
类实现了Lock,它拥有与 synchronized
相同的并发性和内存语义,在现实线程安全的控制中,比较常用的是ReentrantLock
,可以显式枷锁,释放锁。
代码示例
| package com.sanduo.annotation.demo03.gaoji; |
| import java.util.concurrent.locks.ReentrantLock; |
| public class TestReentrantLock { |
| 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; |
| private boolean flag = true; |
| |
| private final ReentrantLock lock = new ReentrantLock(); |
| @Override |
| public void run() { |
| |
| while (flag){ |
| try { |
| buy(); |
| } catch (InterruptedException e) { |
| e.printStackTrace(); |
| } |
| } |
| } |
| |
| private void buy() throws InterruptedException { |
| try { |
| lock.lock(); |
| |
| if(ticketNums <= 0){ |
| flag = false; |
| return; |
| } |
| |
| Thread.sleep(200); |
| |
| System.out.println(ticketNums--); |
| }finally { |
| lock.unlock(); |
| } |
| } |
| } |
synchronized与Lock的对比
- Lock是显式锁(手动开启和关闭,别忘记关闭锁),
synchronized
是隐式锁,出了作用域自动释放
- Lock只有代码块锁,
synchronized
有代码块锁和方法锁
- 使用Lock锁,JVM将花费较少的时间来调度线程,性能更好。并且具有更友好的扩展性(提供更多子类)
- 优先使用顺序
- Lock > 同步代码块(已经进入了方法体,分配了相应资源)> 同步方法(在方法体之外)
5.线程协作
1.管程法
说明
- 生产者:负责生产数据的模块(可能式方法,对象,线程,进程);
- 消费者:负责处理数据的模块(可能式方法,对象,线程,进程);
- 缓冲区:消费者不能直接使用生产者的数据,他们之间有个“缓存区”
生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据
代码示例
| package com.sanduo.annotation.demo03.gaoji; |
| |
| |
| public class TestPC { |
| public static void main(String[] args) { |
| SynContainter synContainter = new SynContainter(); |
| new Productor(synContainter).start(); |
| new Consumer(synContainter).start(); |
| } |
| } |
| |
| class Productor extends Thread{ |
| SynContainter containter; |
| public Productor(SynContainter containter){ |
| this.containter = containter; |
| } |
| |
| @Override |
| public void run() { |
| for (int i = 0; i < 100; i++) { |
| containter.push(new Chicken(i)); |
| System.out.println("生产了"+i+"只鸡"); |
| } |
| } |
| } |
| |
| class Consumer extends Thread{ |
| SynContainter containter; |
| public Consumer(SynContainter containter){ |
| this.containter = containter; |
| } |
| |
| @Override |
| public void run() { |
| for (int i = 0; i < 100; i++) { |
| System.out.println("消费了-->"+containter.pop().id+"只鸡"); |
| |
| } |
| } |
| } |
| |
| class Chicken{ |
| int id; |
| public Chicken(int id) { |
| this.id = id; |
| } |
| } |
| |
| class SynContainter{ |
| |
| 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.信号灯法
代码示例1:演员观众
| package com.sanduo.annotation.demo03.gaoji; |
| |
| 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++) { |
| this.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; |
| } |
| } |
代码示例2:产品经理程序员
| package com.sanduo.annotation.demo03.gaoji; |
| |
| public class TestPc3 { |
| public static void main(String[] args) { |
| Need need = new Need(); |
| new PM(need).start(); |
| new RD(need).start(); |
| } |
| } |
| |
| class PM extends Thread{ |
| Need need; |
| public PM(Need need){ |
| this.need = need; |
| } |
| @Override |
| public void run() { |
| for (int i = 0; i < 20; i++) { |
| if(i%2==0){ |
| this.need.push("需求"); |
| }else{ |
| this.need.push("BUG"); |
| } |
| } |
| } |
| } |
| |
| class RD extends Thread{ |
| Need need; |
| public RD(Need need){ |
| this.need = need; |
| } |
| @Override |
| public void run() { |
| for (int i = 0; i < 20; i++) { |
| this.need.pop(); |
| } |
| } |
| } |
| |
| class Need{ |
| |
| |
| String name; |
| boolean flag = true; |
| |
| public synchronized void push(String name){ |
| if(!flag){ |
| try { |
| this.wait(); |
| } catch (InterruptedException e) { |
| e.printStackTrace(); |
| } |
| } |
| System.out.println("产品经理提出:"+name); |
| this.name = name; |
| this.notifyAll(); |
| this.flag = !this.flag; |
| } |
| |
| public synchronized void pop(){ |
| if(flag){ |
| try { |
| this.wait(); |
| } catch (InterruptedException e) { |
| e.printStackTrace(); |
| } |
| } |
| System.out.println("程序员完成:"+name); |
| this.notifyAll(); |
| this.flag = !this.flag; |
| } |
| } |
3.线程池
说明
- 背景:经常创建和销毁,使用量特别大量的资源,比如并发情况下的线程,对性能影响很大。
- 思路:提前创建好多个线程,放入线程池中,使用虎直接获取,使用完放回池中。
可以避免频繁创建销毁,实现重复利用。类似生活中的公共交通工具。
- 好处
- 提供响应速度(减少了创建线程的时间)
- 降低资源消耗(重复利用线程池中线程,不需要每次都创建)
- 便于线程管理(...)
- corePoolSize:核心池的大小
- maximumPoolSize:最大线程数
- keepAliveTime:线程没有任务时最多保持多久的时间后会终止
- JDK5.0起提供了线程相关API:
ExecutorService
和Executors
ExecutorService
:真正的线程池接口。常见子类ThreadPoolExecutor
- void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable
- Future sumbit(Callable task):执行任务,有返回值,一般用来执行Callable
- void shutdown():关闭连接池
- Executours:工具类、线程池的工厂类,用户创建并返回不同类型的线程池
代码示例
| package com.sanduo.annotation.demo03.gaoji; |
| import java.util.concurrent.ExecutorService; |
| import java.util.concurrent.Executors; |
| public class TestPool { |
| public static void main(String[] args) { |
| 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() { |
| System.out.println(Thread.currentThread().getName()); |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了