• 多线程复习笔记



    🎈线程的三种创建方式

    1. Thread class 继承Thread类
    2. Runnable接口 实现Runnable接口
    3. Callable接口 实现Callable接口(了解)

    继承Thread类

    1. 自定义线程类继承Thread类
    2. 重写run()方法,编写线程执行体
    3. 创建线程对象,调用start()方法启动线程
    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();
    		//调用start()方法开启线程
            testThread1.start();
    
            for (int i =0; i< 1000; i++){
                System.out.println("主线程");
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    在这里插入图片描述

    线程不一定立即执行,CPU安排调度


    实现Runnable接口

    1. 定义MyRunnable类实现Runnable接口
    2. 实现run()方法,编写线程执行体
    3. 创建线程对象,调用start()方法启动线程

    推荐使用Runnable对象.因为Java单继承的局限性

    public class TestThread3 implements Runnable {
        @Override
        public void run() {
    
            for (int i = 0;i < 20;i++){
                System.out.println("我不是主线程");
            }
        }
    
        public static void main(String[] args) {
    
            //创建Runnable接口的实现类对象
            TestThread3 testThread3 = new TestThread3();
    
            //创建线程对象,通过线程对象开启线程,代理
            Thread thread = new Thread(testThread3);
            
            thread.start();
    
            for (int i =0; i< 1000; i++){
                System.out.println("主线程");
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    在这里插入图片描述


    实现Callable接口

    1.实现Callable接口,需要返回值类型
    2.重写call方法,需要抛出异常
    3.创建目标对象
    4.创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1);
    5.提交执行:Future result1 = ser.submit(t1);
    6.获取结果: boolean r1 = result1.get()
    7.关闭服务:ser.shutdownNow();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    🎈并发问题

    public class TestThread4 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();
                }
                //currentThread()代表当前线程 getName()获取线程名
                System.out.println(Thread.currentThread().getName()+"抢到了第"+ticketNums--+"号票");
            }
        }
    
        public static void main(String[] args) {
    
            TestThread4 ticket = new TestThread4();
    
            new Thread(ticket,"肥皂").start();
            new Thread(ticket,"幽灵").start();
            new Thread(ticket,"普莱斯").start();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    结果出现并发问题,两个人抢到了同一张票,线程不安全
    在这里插入图片描述


    静态代理模式

    public class StacticProxy {
        public static void main(String[] args) {
            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 before(){
            System.out.println("婚前布置");
        }
    
        private void after(){
            System.out.println("婚后收钱");
        }
    
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    在这里插入图片描述

    静态代理模式总结;

    • 真实对象和代理对象都要实现同一个按口
    • 代理对象要代理真实角色

    优点:

    • 代理对象可以做很多真实对象做不了的事情
    • 真实对象专注做自己的事情

    🎈线程状态

    在这里插入图片描述
    在这里插入图片描述


    线程停止

    • 建议线程正常停止:利用次数,不建议死循环。
    • 建议使用标志位:设置一个标志位。
    • 不要使用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-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线程开始跑了");
                if (i==900){
                    //调用stop方法切换标志位,让线程停止
                    testStop.stop();
                    System.out.println("该线程已被停止!!!!");
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    在这里插入图片描述


    线程休眠

    • sleep(时间)指定当前线程阻塞的毫秒数;
    • sleep存在异常InterruptedException;
    • sleep时间达到后线程进入就绪状态;
    • sleep可以模拟网络延时,倒计时等。
    • 每一个对象都有一个锁,sleep不会释放锁;

    在这里插入图片描述


    礼让线程

    • 礼让线程,让当前正在执行的线程暂停,但不阻塞
    • 将线程从运行状态转为就绪状态
    • 让cpu重新调度,礼让不一定成功!看CPU心情
    public class TestYield {
    
        public static void main(String[] args) {
            MyYield myYield = new MyYield();
    
            new Thread(myYield,"a").start();
            new Thread(myYield,"b").start();
        }
    }
    
    class MyYield implements Runnable{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+"线程开始");
            Thread.yield();//礼让
            System.out.println(Thread.currentThread().getName()+"线程停止");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    在这里插入图片描述


    Join

    Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞

    public class TestJoin implements Runnable{
        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
                System.out.println("VIP来辣!!!");
            }
        }
    
        public static void main(String[] args) throws InterruptedException{
    
            //启动线程
            TestJoin testJoin = new TestJoin();
            Thread thread = new Thread(testJoin);
            thread.start();
    
            //主线程
            for (int i = 0; i < 500; i++) {
                if (i == 200){
                    thread.join();//插队
                }
                System.out.println("main" + i);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    在这里插入图片描述


    线程状态观测

    在这里插入图片描述
    如何观测:
    在这里插入图片描述


    线程优先级

    • Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。

    • 线程的优先级用数字表示,范围从1~10.

      • Thread.MIN_PRIORITY = 1;
      • Thread.MAX_PRIORITY = 10;
      • Thread.NORM_PRIORITY = 5;
    • 使用以下方式改变或获取优先级
      getPriority() . setPriority(int xxx)

    源码看线程的优先级

    在这里插入图片描述


    守护线程daemon

    • 线程分为用户线程守护线程
    • 虚拟机必须确保用户线程执行完毕
    • 虚拟机不用等待守护线程执行完毕
    • 如,后台记录操作日志,监控内存,垃圾回收等待.

    如何使用

    在这里插入图片描述


    🎈线程同步机制

    处理多线程问题时﹐多个线程访问同一个对象﹐并且某些线程还想修改这个对象.这时候我们就需要线程同步﹒线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程再使用

    • synchronized

    由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized , 当一个线程获得对象的排它锁,独占资源﹐其他线程必须等待,使用后释放锁即可.存在以下问题:

    • 一个线程持有锁会导致其他所有需要此锁的线程挂起;
    • 在多线程竞争下,加锁﹐释放锁会导致比较多的上下文切换和调度延时,引起性能问题;
    • 如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置,引起性能问题.

    三大不安全案例

    public class UnsafeBuyTicket {
        public static void main(String[] args) {
            BuyTicket station = new BuyTicket();
    
            new Thread(station,"肥皂").start();
            new Thread(station,"幽灵").start();
            new Thread(station,"普莱斯").start();
        }
    }
    
    class BuyTicket implements Runnable{
    
        //票
        private int ticketNums = 10;
        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--);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    在这里插入图片描述


    public class UnsafeBank {
        public static void main(String[] args) {
            //账户一共100
            Account account = new Account(100,"资金");
    
            //你取50,他取100
            Drawing no1 = new Drawing(account,50,"一号");
            Drawing no2 = new Drawing(account,100,"二号");
    
            no1.start();
            no2.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);
    
            //这里的this指代Thread
            System.out.println(this.getName()+"手里的钱:"+nowMoney);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71

    在这里插入图片描述


    import java.util.ArrayList;
    import java.util.List;
    
    public class UnsafeList {
        public static void main(String[] args) {
            List<String> list = new ArrayList<String>();
            for (int i = 0; i < 10000; i++) {
                new Thread(()->{
                    list.add(Thread.currentThread().getName());
                }).start();
            }
            System.out.println(list.size());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    在这里插入图片描述
    因为:可能两个线程同一瞬间把两个数组添加到同一位置


    同步方法、同步块

    思路

    • 由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包括两种用法︰synchronized方法和synchronized块.
      • 同步方法:public synchronized void method(int args)0
    • synchronized方法控制对“对象”的访问﹐每个对象对应一把锁﹐每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行﹐就独占该锁,直到该方法返回才释放锁﹐后面被阻塞的线程才能获得这个锁,继续执行
      • 缺陷:若将一个大的方法申明为synchronized将会影响效率

    同步块

    • 同步块:synchronized (Obj ){ }
    • Obj称之为同步监视器
      • Obj可以是任何对象﹐但是推荐使用共享资源作为同步监视器
      • 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,为这个对象本身,或者是class [反射中讲解]
    • 同步监视器的执行过程
      1. 第一个线程访问,锁定同步监视器,执行其中代码。
      2. 第二个线程访问,发现同步监视器被锁定﹐无法访问
      3. 第一个线程访问完毕,解锁同步监视器
      4. 第二个线程访问,发现同步监视器没有锁﹐然后锁定并访问

    改进前面的代码

    synchronized同步方法,默认锁的是this

    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();
                }
            }
        }
    
        //synchronized同步方法,默认锁的是this
        private synchronized void buy() throws InterruptedException {
            //判断是否有票
            if (ticketNums<=0){
                flag = false;
                return;
            }
            //模拟演示
    
            Thread.sleep(100);
    
            //买票
            System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    共享资源account为同步监视器

    public class UnsafeBank {
        public static void main(String[] args) {
            //账户一共100
            Account account = new Account(100,"资金");
    
            //你取50,他取100
            Drawing no1 = new Drawing(account,50,"一号");
            Drawing no2 = new Drawing(account,100,"二号");
    
            no1.start();
            no2.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() { //锁run没用
    
            //共享资源account为同步监视器
            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);
    
                //这里的this指代Thread
                System.out.println(this.getName()+"手里的钱:"+nowMoney);
            }
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75

    要往list里添加数据,list为共享数据,为同步监视器

    import java.util.ArrayList;
    import java.util.List;
    
    public class UnsafeList {
        public static void main(String[] args) {
            List<String> list = new ArrayList<String>();
            for (int i = 0; i < 10000; i++) {
                new Thread(()->{
                    //要往list里添加数据,list为共享数据
                    synchronized (list){
                        list.add(Thread.currentThread().getName());
                    }
                }).start();
            }
            System.out.println(list.size());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    死锁

    多个线程各自占有一些共享资源﹐并且互相等待其他线程占有的资源才能运行﹐而导致两个或者多个线程都在等待对方释放资源﹐都停止执行的情形.某一个同步块同时拥有“两个以上对象的锁”时,就可能会发生“死锁”的问题.

    • 产生死锁的四个必要条件:

      1. 互斥条件:一个资源每次只能被一个进程使用。
      2. 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放。
      3. 不剥夺条件:进程已获得的资源,在末使用完之前,不能强行剥夺。
      4. 循环等待条件∶若干进程之间形成一种头尾相接的循环等待资源关系。
    • 死锁演示

    //死锁:多个线程互相拿着对方需要的资源,然后形成僵持.
    public class DeadLock {
    
        public static void main(String[] args) {
            Makeup g1 = new Makeup(0,"女主");
            Makeup g2 = new Makeup(1,"女配");
    
            g1.start();
            g2.start();
        }
    }
    
    
    //口红
    class Lipstick{
    
    }
    
    //镜子
    class Mirror{
    
    }
    
    //化妆
    class Makeup extends Thread {
    
        //需要的资源只有一份,用静态static来保证
        static Lipstick lipstick = new Lipstick();
        static Mirror mirror = new Mirror();
    
    
        int choice;//选择
        String girlName;//使用口红的人
    
        Makeup(int choice, String girlName) {
            this.choice = choice;
            this.girlName = girlName;
        }
    
        @Override
        public void run() {
            //化妆
            try {
                makeup();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
        //化妆,互相持有对方的锁,就是需要拿到对方的资源
        //一个拿口红锁,另一个人拿镜子锁,然后谁都无法进行下一步
        private void makeup() throws InterruptedException {
            if (choice == 0) {
                synchronized (lipstick) { //获得口红的锁
                    System.out.println(this.girlName + "获得口红的锁");
                    Thread.sleep(1000);
    
                    synchronized (mirror) { //sleep后想获得镜子
                        System.out.println(this.girlName + "获得镜子的锁");
                    }
                }
            } else {
                synchronized (mirror) { //获得口红的锁
                    System.out.println(this.girlName + "获得镜子的锁");
                    Thread.sleep(2000);
    
                    synchronized (lipstick) { //sleep后想获得镜子
                        System.out.println(this.girlName + "获得口红的锁");
                    }
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73

    卡住了
    在这里插入图片描述

    • 解决办法,拿出锁来,这样一方即使拿到锁,在使用完后会释放,另一方就会拿到,避免死锁。
    //死锁:多个线程互相拿着对方需要的资源,然后形成僵持.
    public class DeadLock {
    
        public static void main(String[] args) {
            Makeup g1 = new Makeup(0,"女主");
            Makeup g2 = new Makeup(1,"女配");
    
            g1.start();
            g2.start();
        }
    }
    
    
    //口红
    class Lipstick{
    
    }
    
    //镜子
    class Mirror{
    
    }
    
    //化妆
    class Makeup extends Thread {
    
        //需要的资源只有一份,用静态static来保证
        static Lipstick lipstick = new Lipstick();
        static Mirror mirror = new Mirror();
    
    
        int choice;//选择
        String girlName;//使用口红的人
    
        Makeup(int choice, String girlName) {
            this.choice = choice;
            this.girlName = girlName;
        }
    
        @Override
        public void run() {
            //化妆
            try {
                makeup();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
        //化妆,互相持有对方的锁,就是需要拿到对方的资源
        //一个拿口红锁,另一个人拿镜子锁,然后谁都无法进行下一步
        private void makeup() throws InterruptedException {
            if (choice == 0) {
                synchronized (lipstick) { //获得口红的锁
                    System.out.println(this.girlName + "获得口红的锁");
                    Thread.sleep(1000);
    
                }
                synchronized (mirror) { //sleep后想获得镜子
                    System.out.println(this.girlName + "获得镜子的锁");
                }
            } else {
                synchronized (mirror) { //获得口红的锁
                    System.out.println(this.girlName + "获得镜子的锁");
                    Thread.sleep(2000);
                    
                }
                synchronized (lipstick) { //sleep后想获得镜子
                    System.out.println(this.girlName + "获得口红的锁");
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73

    在这里插入图片描述


    生产者消费者问题

    应用场景∶

    • 假设仓库中只能存放一件产品﹐生产者将生产出来的产品放入仓库﹐消费者将仓库中产品取走消费.
    • 如果仓库中没有产品,则生产者将产品放入仓库,否则停止生产并等待,直到仓库中的产品被消费者取走为止.
    • 如果仓库中放有产品﹐则消费者可以将产品取走消费,否则停止消费并等待,直到仓库中再次放入产品为止

    在这里插入图片描述
    在这里插入图片描述

    在这里插入图片描述


    管程法

    //测试:生产者消费者模型-->利用缓冲区解决:管程法
    
    public class TestPC {
    
        public static void main(String[] args) {
            SynContainer container = new SynContainer();
    
            new Productor(container).start();
            new Consumer(container).start();
        }
    }
    
    //生产者
    class Productor extends Thread{
        SynContainer container;
    
        public Productor(SynContainer container){
            this.container = container;
        }
    
        //生产
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                container.push(new Chicken(i));
                System.out.println("生产了第"+i+"只鸡");
            }
        }
    }
    
    //消费者
    class Consumer extends Thread{
        SynContainer container;
    
        public Consumer(SynContainer container){
            this.container = container;
        }
    
        //消费
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                System.out.println("消费了第"+container.pop().id+"只鸡");
            }
        }
    }
    
    //产品
    class Chicken{
        int id; //产品编号
    
        public Chicken(int id) {
            this.id = id;
        }
    }
    
    //缓冲区
    class SynContainer{
    
        //需要一个容器大小
        Chicken[] chickens = new Chicken[10];
        //容器计数器
        int count = 0;
    
        //生产者放入产品
        public synchronized void push(Chicken chicken){
            //如果容器满了,就需要等待消费者消费
            if (count==chickens.length){
                //通知消费者消费,生产等待
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //如果没有满。我们就需要丢入产品
            chickens[count]=chicken;
            count++;
    
            //可以通知消费者消费了
            this.notifyAll();
        }
    
    
        //消费者消费产品
        public synchronized  Chicken pop(){
            //判断是否能消费
            if (count==0){
                //等待生产者生产,消费者等待
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    
            //如果可以消费
            count--;
            Chicken chicken = chickens[count];
    
            //吃完了,通知消费者生产
            this.notifyAll();
            return chicken;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105

    在这里插入图片描述


    信号灯法

    public class TestPc2 {
        public static void main(String[] args) {
            TV tv = new TV();
    
            new Player(tv).start();
            new Watcher(tv).start();
        }
    }
    
    //生产者:演员
    class Player extends Thread{
        TV tv;
        public Player(TV tv){
            this.tv = tv;
        }
    
        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                if (i%2==0){
                    this.tv.play("进击的巨人");
                }else {
                    this.tv.play("广告");
                }
            }
        }
    }
    
    //消费者:观众
    class Watcher extends Thread{
        TV tv;
        public Watcher(TV tv){
            this.tv = tv;
        }
    
        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                tv.watch();
            }
        }
    }
    
    //产品:节目
    class TV{
        //演员表演,观众等待
        //观众观看后,演员等待
        String voice; //表演的节目
        boolean flag = true;
    
        //表演
        public  synchronized void play(String voice){
    
            if (!flag){
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    
            System.out.println("演员表演了:"+voice);
            //通知观众观看
            this.notifyAll(); //通知唤醒
            this.voice = voice;
            this.flag = !this.flag; //取反永远保持最新
        }
    
        //观看
        public synchronized void watch() {
            if (flag) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    
            System.out.println("观众观看了:"+voice);
            //通知演员表演
            this.notifyAll();
            this.flag = !this.flag;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84

    在这里插入图片描述


    🎈补充JUC知识点

    测试JUC安全类型的集合

    import java.util.concurrent.CopyOnWriteArrayList;
    
    //测试JUC安全类型的集合
    public class TestJUC {
        public static void main(String[] args) {
            CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
            for (int i = 0; i < 10000; i++) {
                new Thread(()->{
                    list.add(Thread.currentThread().getName());
                }).start();
            }
    
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            System.out.println(list.size());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    在这里插入图片描述


    Lock(锁)

    • 从JDK 5.0开始,Java提供了更强大的线程同步机制——通过显式定义同步锁对象来实现同步。同步锁使用Lock对象充当
    • java.util.concurrent.locks.Lock接口是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象
    • ReentrantLock类实现了Lock,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显式加锁、释放锁。

    Lock
    如果同步代码有异常,要将unlock()写入finally语句块
    在这里插入图片描述

    import java.util.concurrent.locks.ReentrantLock;
    
    public class TestLock {
        public static void main(String[] args) {
            TestLock2 testLock2 = new TestLock2();
    
            //跑三个线程
            new Thread(testLock2).start();
            new Thread(testLock2).start();
            new Thread(testLock2).start();
        }
    }
    
    class TestLock2 implements Runnable{
    
        int ticketNums = 10;
    
        //定义Lock锁
        private final ReentrantLock lock = new ReentrantLock();
        
        @Override
        public void run() {
            while (true){
    
                try {
                    lock.lock(); //加锁
    
                    if (ticketNums>0){
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(ticketNums--);
                    }else{
                        break;
                    }
                }finally { //如果同步代码有异常,要将unlock()写入finally语句块
                    lock.unlock();//解锁
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    在这里插入图片描述

    synchronized 与Lock的对比

    • Lock是显式锁(手动开启和关闭锁,别忘记关闭锁) synchronized是隐式锁,出了作用域自动释放
    • Lock只有代码块锁,synchronized有代码块锁和方法锁
    • 使用Lock锁,JVM将花费较少的时间来调度线程,性能更好。并且具有更好的扩展性(提供更多的子类)
    • 优先使用顺序:
      • Lock >同步代码块(已经进入了方法体,分配了相应资源)>同步方法(在方法体之外)

    🎈使用线程池

    • 背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。
    • 思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。类似生活中的公共交通工具。
    • 好处:
      • 提高响应速度(减少了创建新线程的时间)
      • 降低资源消耗(重复利用线程池中线程,不需要每次都创建)
      • 便于线程管理(…)
        • corePoolSize:核心池的大小
        • maximumPoolSize:最大线程数
        • keepAliveTime:线程没有任务时最多保持多长时间后会终止
    * JDK 5.0起提供了线程池相关API: ExecutorService和* ExecutorsExecutorService:真正的线程池接口。常见子类ThreadPoolExecuutor
      * void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable
      *  Future submit(Callable task):执行任务,有返回值,一般又来执行Callable
      * void shutdown():关闭连接池
    * Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池
    
    • 1
    • 2
    • 3
    • 4
    • 5
    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.shutdown();
        }
    }
    
    class MyThread implements Runnable{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    在这里插入图片描述

  • 相关阅读:
    【教学类-12-01】20221105《连连看8*4-不重复16个)(小班主题《白天与黑夜》)
    网络编程TCP/UDP通信
    ZKP3.2 Programming ZKPs (Arkworks & Zokrates)
    MFC中LIST控件的问题
    为什么使用前端框架
    [论文笔记] Balboa: Bobbing and Weaving around Network Censorship
    Spring Cloud/Boot启动报错Consider defining a bean of type ServerCodecConfigurer
    个人所得税思维导图参考 —— 筑梦之路
    DiskSim 4.0安装详细流程(基于Ubuntu14 32位系统)
    小工具——筛选图像小工具
  • 原文地址:https://blog.csdn.net/weixin_48063660/article/details/127655092