Java多线程02

打印 上一主题 下一主题

主题 576|帖子 576|积分 1728

1. 线程池

1.1 线程状态先容

当线程被创建并启动以后,它既不是一启动就进入了执行状态,也不是一直处于执行状态。线程对象在差别的时期有差别的状态。那么Java中的线程存在哪几种状态呢?Java中的线程
状态被定义在了java.lang.Thread.State罗列类中,State罗列类的源码如下:
  1. public class Thread {
  2.    
  3.     public enum State {
  4.    
  5.         /* 新建 */
  6.         NEW ,
  7.         /* 可运行状态 */
  8.         RUNNABLE ,
  9.         /* 阻塞状态 */
  10.         BLOCKED ,
  11.         /* 无限等待状态 */
  12.         WAITING ,
  13.         /* 计时等待 */
  14.         TIMED_WAITING ,
  15.         /* 终止 */
  16.         TERMINATED;
  17.    
  18.         }
  19.    
  20.     // 获取当前线程的状态
  21.     public State getState() {
  22.         return jdk.internal.misc.VM.toThreadState(threadStatus);
  23.     }
  24.    
  25. }
复制代码
通过源码我们可以看到Java中的线程存在6种状态,每种线程状态的寄义如下
线程状态详细寄义NEW一个尚未启动的线程的状态。也称之为初始状态、开始状态。线程刚被创建,但是并未启动。还没调用start方法。MyThread t = new MyThread()只有线程象,没有线程特性。RUNNABLE当我们调用线程对象的start方法,那么此时线程对象进入了RUNNABLE状态。那么此时才是真正的在JVM历程中创建了一个线程,线程一经启动并不是立刻得到执行,线程的运行与否要听令与CPU的调度,那么我们把这个中间状态称之为可执行状态(RUNNABLE)也就是说它具备执行的资格,但是并没有真正的执行起来而是在等待CPU的度。BLOCKED当一个线程试图获取一个对象锁,而该对象锁被其他的线程持有,则该线程进入Blocked状态;当该线程持有锁时,该线程将酿成Runnable状态。WAITING一个正在等待的线程的状态。也称之为等待状态。造成线程等待的原因有两种,分别是调用Object.wait()、join()方法。处于等待状态的线程,正在等待其他线程去执行一个特定的操作。例如:因为wait()而等待的线程正在等待另一个线程去调用notify()或notifyAll();一个因为join()而等待的线程正在等待另一个线程结束。TIMED_WAITING一个在限定时间内等待的线程的状态。也称之为限时等待状态。造成线程限时等待状态的原因有三种,分别是:Thread.sleep(long),Object.wait(long)、join(long)。TERMINATED一个完全运行完成的线程的状态。也称之为终止状态、结束状态 各个状态的转换,如下图所示:

1.2 线程池-根本原理

概述 :
​ 提到池,各人应该能想到的就是水池。水池就是一个容器,在该容器中存储了许多的水。那么什么是线程池呢?线程池也是可以看做成一个池子,在该池子中存储许多个线程。
线程池存在的意义:
​ 体系创建一个线程的成本是比力高的,因为它涉及到与操作体系交互,当程序中必要创建大量生存期很短暂的线程时,频繁的创建和烧毁线程对体系的资源消耗有可能大于业务处理是对系
​ 统资源的消耗,这样就有点"本末倒置"了。针对这一种环境,为了提高性能,我们就可以采用线程池。线程池在启动的时,会创建大量空闲线程,当我们向线程池提交任务的时,线程池就
​ 会启动一个线程来执行该任务。等待任务执行完毕以后,线程并不会死亡,而是再次返回到线程池中称为空闲状态。等待下一次任务的执行。
线程池的计划思路 :

  • 准备一个任务容器
  • 一次性启动多个(2个)消耗者线程
  • 刚开始任务容器是空的,以是线程都在wait
  • 直到一个外部线程向这个任务容器中扔了一个"任务",就会有一个消耗者线程被唤醒
  • 这个消耗者线程取出"任务",而且执行这个任务,执行完毕后,继续等待下一次任务的到来
1.3 线程池-Executors默认线程池

概述 : JDK对线程池也进行了相关的实现,在真实企业开发中我们也很少去自定义线程池,而是使用JDK中自带的线程池。
我们可以使用Executors中所提供的静态方法来创建线程池
​ static ExecutorService newCachedThreadPool() 创建一个默认的线程池
​ static newFixedThreadPool(int nThreads) 创建一个指定最多线程数目的线程池
代码实现 :
  1. package com.itheima.mythreadpool;
  2. //static ExecutorService newCachedThreadPool()   创建一个默认的线程池
  3. //static newFixedThreadPool(int nThreads)            创建一个指定最多线程数量的线程池
  4. import java.util.concurrent.ExecutorService;
  5. import java.util.concurrent.Executors;
  6. public class MyThreadPoolDemo {
  7.     public static void main(String[] args) throws InterruptedException {
  8.         //1,创建一个默认的线程池对象.池子中默认是空的.默认最多可以容纳int类型的最大值.
  9.         ExecutorService executorService = Executors.newCachedThreadPool();
  10.         //Executors --- 可以帮助我们创建线程池对象
  11.         //ExecutorService --- 可以帮助我们控制线程池
  12.         executorService.submit(()->{
  13.             System.out.println(Thread.currentThread().getName() + "在执行了");
  14.         });
  15.         //Thread.sleep(2000);
  16.         executorService.submit(()->{
  17.             System.out.println(Thread.currentThread().getName() + "在执行了");
  18.         });
  19.         executorService.shutdown();
  20.     }
  21. }
复制代码
1.4 线程池-Executors创建指定上限的线程池

使用Executors中所提供的静态方法来创建线程池
​ static ExecutorService newFixedThreadPool(int nThreads) : 创建一个指定最多线程数目的线程池
代码实现 :
  1. package com.itheima.mythreadpool;
  2. //static ExecutorService newFixedThreadPool(int nThreads)
  3. //创建一个指定最多线程数量的线程池
  4. import java.util.concurrent.ExecutorService;
  5. import java.util.concurrent.Executors;
  6. import java.util.concurrent.ThreadPoolExecutor;
  7. public class MyThreadPoolDemo2 {
  8.     public static void main(String[] args) {
  9.         //参数不是初始值而是最大值
  10.         ExecutorService executorService = Executors.newFixedThreadPool(10);
  11.         ThreadPoolExecutor pool = (ThreadPoolExecutor) executorService;
  12.         System.out.println(pool.getPoolSize());//0
  13.         executorService.submit(()->{
  14.             System.out.println(Thread.currentThread().getName() + "在执行了");
  15.         });
  16.         executorService.submit(()->{
  17.             System.out.println(Thread.currentThread().getName() + "在执行了");
  18.         });
  19.         System.out.println(pool.getPoolSize());//2
  20. //        executorService.shutdown();
  21.     }
  22. }
复制代码
1.5 线程池-ThreadPoolExecutor

创建线程池对象 :
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(焦点线程数目,最大线程数目,空闲线程最大存活时间,任务队列,创建线程工厂,任务的拒绝策略);
代码实现 :
  1. package com.itheima.mythreadpool;
  2. import java.util.concurrent.ArrayBlockingQueue;
  3. import java.util.concurrent.Executors;
  4. import java.util.concurrent.ThreadPoolExecutor;
  5. import java.util.concurrent.TimeUnit;
  6. public class MyThreadPoolDemo3 {
  7. //    参数一:核心线程数量
  8. //    参数二:最大线程数
  9. //    参数三:空闲线程最大存活时间
  10. //    参数四:时间单位
  11. //    参数五:任务队列
  12. //    参数六:创建线程工厂
  13. //    参数七:任务的拒绝策略
  14.     public static void main(String[] args) {
  15.         ThreadPoolExecutor pool = new ThreadPoolExecutor(2,5,2,TimeUnit.SECONDS,new ArrayBlockingQueue<>(10), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
  16.         pool.submit(new MyRunnable());
  17.         pool.submit(new MyRunnable());
  18.         pool.shutdown();
  19.     }
  20. }
复制代码
1.6 线程池-参数详解


  1. public ThreadPoolExecutor(int corePoolSize,
  2.                               int maximumPoolSize,
  3.                               long keepAliveTime,
  4.                               TimeUnit unit,
  5.                               BlockingQueue<Runnable> workQueue,
  6.                               ThreadFactory threadFactory,
  7.                               RejectedExecutionHandler handler)
  8.    
  9. corePoolSize:   核心线程的最大值,不能小于0
  10. maximumPoolSize:最大线程数,不能小于等于0,maximumPoolSize >= corePoolSize
  11. keepAliveTime:  空闲线程最大存活时间,不能小于0
  12. unit:           时间单位
  13. workQueue:      任务队列,不能为null
  14. threadFactory:  创建线程工厂,不能为null      
  15. handler:        任务的拒绝策略,不能为null  
复制代码
1.7 线程池-非默认任务拒绝策略

RejectedExecutionHandler是jdk提供的一个任务拒绝策略接口,它下面存在4个子类。
  1. ThreadPoolExecutor.AbortPolicy:                     丢弃任务并抛出RejectedExecutionException异常。是默认的策略。
  2. ThreadPoolExecutor.DiscardPolicy:                    丢弃任务,但是不抛出异常 这是不推荐的做法。
  3. ThreadPoolExecutor.DiscardOldestPolicy:    抛弃队列中等待最久的任务 然后把当前任务加入队列中。
  4. ThreadPoolExecutor.CallerRunsPolicy:        调用任务的run()方法绕过线程池直接执行。
复制代码
注:明白线程池对多可执行的任务数 = 队列容量 + 最大线程数
案例演示1:演示ThreadPoolExecutor.AbortPolicy任务处理策略
  1. public class ThreadPoolExecutorDemo01 {
  2.     public static void main(String[] args) {
  3.         /**
  4.          * 核心线程数量为1 , 最大线程池数量为3, 任务容器的容量为1 ,空闲线程的最大存在时间为20s
  5.          */
  6.         ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1 , 3 , 20 , TimeUnit.SECONDS ,
  7.                 new ArrayBlockingQueue<>(1) , Executors.defaultThreadFactory() , new ThreadPoolExecutor.AbortPolicy()) ;
  8.         // 提交5个任务,而该线程池最多可以处理4个任务,当我们使用AbortPolicy这个任务处理策略的时候,就会抛出异常
  9.         for(int x = 0 ; x < 5 ; x++) {
  10.             threadPoolExecutor.submit(() -> {
  11.                 System.out.println(Thread.currentThread().getName() + "---->> 执行了任务");
  12.             });
  13.         }
  14.     }
  15. }
复制代码
控制台输出效果
  1. pool-1-thread-1---->> 执行了任务
  2. pool-1-thread-3---->> 执行了任务
  3. pool-1-thread-2---->> 执行了任务
  4. pool-1-thread-3---->> 执行了任务
复制代码
控制台报错,仅仅执行了4个任务,有一个任务被丢弃了
案例演示2:演示ThreadPoolExecutor.DiscardPolicy任务处理策略
  1. public class ThreadPoolExecutorDemo02 {
  2.     public static void main(String[] args) {
  3.         /**
  4.          * 核心线程数量为1 , 最大线程池数量为3, 任务容器的容量为1 ,空闲线程的最大存在时间为20s
  5.          */
  6.         ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1 , 3 , 20 , TimeUnit.SECONDS ,
  7.                 new ArrayBlockingQueue<>(1) , Executors.defaultThreadFactory() , new ThreadPoolExecutor.DiscardPolicy()) ;
  8.         // 提交5个任务,而该线程池最多可以处理4个任务,当我们使用DiscardPolicy这个任务处理策略的时候,控制台不会报错
  9.         for(int x = 0 ; x < 5 ; x++) {
  10.             threadPoolExecutor.submit(() -> {
  11.                 System.out.println(Thread.currentThread().getName() + "---->> 执行了任务");
  12.             });
  13.         }
  14.     }
  15. }
复制代码
控制台输出效果
  1. pool-1-thread-1---->> 执行了任务
  2. pool-1-thread-1---->> 执行了任务
  3. pool-1-thread-3---->> 执行了任务
  4. pool-1-thread-2---->> 执行了任务
复制代码
控制台没有报错,仅仅执行了4个任务,有一个任务被丢弃了
案例演示3:演示ThreadPoolExecutor.DiscardOldestPolicy任务处理策略
  1. public class ThreadPoolExecutorDemo02 {
  2.     public static void main(String[] args) {
  3.         /**
  4.          * 核心线程数量为1 , 最大线程池数量为3, 任务容器的容量为1 ,空闲线程的最大存在时间为20s
  5.          */
  6.         ThreadPoolExecutor threadPoolExecutor;
  7.         threadPoolExecutor = new ThreadPoolExecutor(1 , 3 , 20 , TimeUnit.SECONDS ,
  8.                 new ArrayBlockingQueue<>(1) , Executors.defaultThreadFactory() , new ThreadPoolExecutor.DiscardOldestPolicy());
  9.         // 提交5个任务
  10.         for(int x = 0 ; x < 5 ; x++) {
  11.             // 定义一个变量,来指定指定当前执行的任务;这个变量需要被final修饰
  12.             final int y = x ;
  13.             threadPoolExecutor.submit(() -> {
  14.                 System.out.println(Thread.currentThread().getName() + "---->> 执行了任务" + y);
  15.             });     
  16.         }
  17.     }
  18. }
复制代码
控制台输出效果
  1. pool-1-thread-2---->> 执行了任务2
  2. pool-1-thread-1---->> 执行了任务0
  3. pool-1-thread-3---->> 执行了任务3
  4. pool-1-thread-1---->> 执行了任务4
复制代码
由于任务1在线程池中等待时间最长,因此任务1被丢弃。
案例演示4:演示ThreadPoolExecutor.CallerRunsPolicy任务处理策略
  1. public class ThreadPoolExecutorDemo04 {
  2.     public static void main(String[] args) {
  3.         /**
  4.          * 核心线程数量为1 , 最大线程池数量为3, 任务容器的容量为1 ,空闲线程的最大存在时间为20s
  5.          */
  6.         ThreadPoolExecutor threadPoolExecutor;
  7.         threadPoolExecutor = new ThreadPoolExecutor(1 , 3 , 20 , TimeUnit.SECONDS ,
  8.                 new ArrayBlockingQueue<>(1) , Executors.defaultThreadFactory() , new ThreadPoolExecutor.CallerRunsPolicy());
  9.         // 提交5个任务
  10.         for(int x = 0 ; x < 5 ; x++) {
  11.             threadPoolExecutor.submit(() -> {
  12.                 System.out.println(Thread.currentThread().getName() + "---->> 执行了任务");
  13.             });
  14.         }
  15.     }
  16. }
复制代码
控制台输出效果
  1. pool-1-thread-1---->> 执行了任务
  2. pool-1-thread-3---->> 执行了任务
  3. pool-1-thread-2---->> 执行了任务
  4. pool-1-thread-1---->> 执行了任务
  5. main---->> 执行了任务
复制代码
通过控制台的输出,我们可以看到次策略没有通过线程池中的线程执行任务,而是直接调用任务的run()方法绕过线程池直接执行。
2. 多线程综合练习

练习一:售票

需求:
​ 一共有1000张影戏票,可以在两个窗口领取,假设每次领取的时间为3000毫秒,
​ 请用多线程模仿卖票过程并打印剩余影戏票的数目
代码示例:
  1. public class MyThread extends Thread {
  2.     //第一种方式实现多线程,测试类中MyThread会创建多次,所以需要加static
  3.     static int ticket = 1000;
  4.     @Override
  5.     public void run() {
  6.         //1.循环
  7.         while (true) {
  8.             //2.同步代码块
  9.             synchronized (MyThread.class) {
  10.                 //3.判断共享数据(已经到末尾)
  11.                 if (ticket == 0) {
  12.                     break;
  13.                 } else {
  14.                     //4.判断共享数据(没有到末尾)
  15.                     try {
  16.                         Thread.sleep(3000);
  17.                     } catch (InterruptedException e) {
  18.                         e.printStackTrace();
  19.                     }
  20.                     ticket--;
  21.                     System.out.println(getName() + "在卖票,还剩下" + ticket + "张票!!!");
  22.                 }
  23.             }
  24.         }
  25.     }
  26. }
  27. public class Test {
  28.     public static void main(String[] args) {
  29.        /*
  30.             一共有1000张电影票,可以在两个窗口领取,假设每次领取的时间为3000毫秒,
  31.             要求:请用多线程模拟卖票过程并打印剩余电影票的数量
  32.         */
  33.         //创建线程对象
  34.         MyThread t1 = new MyThread();
  35.         MyThread t2 = new MyThread();
  36.         //给线程设置名字
  37.         t1.setName("窗口1");
  38.         t2.setName("窗口2");
  39.         //开启线程
  40.         t1.start();
  41.         t2.start();
  42.     }
  43. }
复制代码
练习二:赠予礼物

需求:
​ 有100份礼品,两人同时发送,当剩下的礼品小于10份的时候则不再送出。
​ 利用多线程模仿该过程并将线程的名字和礼物的剩余数目打印出来.
  1. public class MyRunable implements Runnable {
  2.     //第二种方式实现多线程,测试类中MyRunable只创建一次,所以不需要加static
  3.     int count = 100;
  4.     @Override
  5.     public void run() {
  6.         //1.循环
  7.         while (true) {
  8.             //2.同步代码块
  9.             synchronized (MyThread.class) {
  10.                 //3.判断共享数据(已经到末尾)
  11.                 if (count < 10) {
  12.                     System.out.println("礼物还剩下" + count + "不再赠送");
  13.                     break;
  14.                 } else {
  15.                     //4.判断共享数据(没有到末尾)
  16.                     count--;
  17.                     System.out.println(Thread.currentThread().getName() + "在赠送礼物,还剩下" + count + "个礼物!!!");
  18.                 }
  19.             }
  20.         }
  21.     }
  22. }
  23. public class Test {
  24.     public static void main(String[] args) {
  25.         /*
  26.             有100份礼品,两人同时发送,当剩下的礼品小于10份的时候则不再送出,
  27.             利用多线程模拟该过程并将线程的名字和礼物的剩余数量打印出来.
  28.         */
  29.         //创建参数对象
  30.         MyRunable mr = new MyRunable();
  31.         //创建线程对象
  32.         Thread t1 = new Thread(mr,"窗口1");
  33.         Thread t2 = new Thread(mr,"窗口2");
  34.         //启动线程
  35.         t1.start();
  36.         t2.start();
  37.     }
  38. }
复制代码
练习三:打印数字

需求:
​ 同时开启两个线程,共同获取1-100之间的所有数字。
​ 将输出所有的奇数。
  1. public class MyRunable implements Runnable {
  2.     //第二种方式实现多线程,测试类中MyRunable只创建一次,所以不需要加static
  3.     int number = 1;
  4.     @Override
  5.     public void run() {
  6.         //1.循环
  7.         while (true) {
  8.             //2.同步代码块
  9.             synchronized (MyThread.class) {
  10.                 //3.判断共享数据(已经到末尾)
  11.                 if (number > 100) {
  12.                     break;
  13.                 } else {
  14.                     //4.判断共享数据(没有到末尾)
  15.                     if(number % 2 == 1){
  16.                         System.out.println(Thread.currentThread().getName() + "打印数字" + number);
  17.                     }
  18.                     number++;
  19.                 }
  20.             }
  21.         }
  22.     }
  23. }
  24. public class Test {
  25.     public static void main(String[] args) {
  26.         /*
  27.            同时开启两个线程,共同获取1-100之间的所有数字。
  28.            要求:将输出所有的奇数。
  29.         */
  30.         //创建参数对象
  31.         MyRunable mr = new MyRunable();
  32.         //创建线程对象
  33.         Thread t1 = new Thread(mr,"线程A");
  34.         Thread t2 = new Thread(mr,"线程B");
  35.         //启动线程
  36.         t1.start();
  37.         t2.start();
  38.     }
  39. }
复制代码
练习四:抢红包

需求:
​ 抢红包也用到了多线程。
​ 假设:100块,分成了3个包,如今有5个人去抢。
​ 其中,红包是共享数据。
​ 5个人是5条线程。
​ 打印效果如下:
​ XXX抢到了XXX元
​ XXX抢到了XXX元
  1.          XXX抢到了XXX元
  2.         XXX没抢到
  3.         XXX没抢到
复制代码
解决方案一:
  1. public class MyThread extends Thread{
  2.     //共享数据
  3.     //100块,分成了3个包
  4.     static double money = 100;
  5.     static int count = 3;
  6.     //最小的中奖金额
  7.     static final double MIN = 0.01;
  8.     @Override
  9.     public void run() {
  10.         //同步代码块
  11.         synchronized (MyThread.class){
  12.             if(count == 0){
  13.                 //判断,共享数据是否到了末尾(已经到末尾)
  14.                 System.out.println(getName() + "没有抢到红包!");
  15.             }else{
  16.                 //判断,共享数据是否到了末尾(没有到末尾)
  17.                 //定义一个变量,表示中奖的金额
  18.                 double prize = 0;
  19.                 if(count == 1){
  20.                     //表示此时是最后一个红包
  21.                     //就无需随机,剩余所有的钱都是中奖金额
  22.                     prize = money;
  23.                 }else{
  24.                     //表示第一次,第二次(随机)
  25.                     Random r = new Random();
  26.                     //100 元   3个包
  27.                     //第一个红包:99.98
  28.                     //100 - (3-1) * 0.01
  29.                     double bounds = money - (count - 1) * MIN;
  30.                     prize = r.nextDouble(bounds);
  31.                     if(prize < MIN){
  32.                         prize = MIN;
  33.                     }
  34.                 }
  35.                 //从money当中,去掉当前中奖的金额
  36.                 money = money - prize;
  37.                 //红包的个数-1
  38.                 count--;
  39.                 //本次红包的信息进行打印
  40.                 System.out.println(getName() + "抢到了" + prize + "元");
  41.             }
  42.         }
  43.     }
  44. }
  45. public class Test {
  46.     public static void main(String[] args) {
  47.         /*
  48.             微信中的抢红包也用到了多线程。
  49.             假设:100块,分成了3个包,现在有5个人去抢。
  50.             其中,红包是共享数据。
  51.             5个人是5条线程。
  52.             打印结果如下:
  53.                     XXX抢到了XXX元
  54.                     XXX抢到了XXX元
  55.                     XXX抢到了XXX元
  56.                     XXX没抢到
  57.                     XXX没抢到
  58.         */
  59.         //创建线程的对象
  60.         MyThread t1 = new MyThread();
  61.         MyThread t2 = new MyThread();
  62.         MyThread t3 = new MyThread();
  63.         MyThread t4 = new MyThread();
  64.         MyThread t5 = new MyThread();
  65.         //给线程设置名字
  66.         t1.setName("小A");
  67.         t2.setName("小QQ");
  68.         t3.setName("小哈哈");
  69.         t4.setName("小诗诗");
  70.         t5.setName("小丹丹");
  71.         //启动线程
  72.         t1.start();
  73.         t2.start();
  74.         t3.start();
  75.         t4.start();
  76.         t5.start();
  77.     }
  78. }
复制代码
解决方案二:
  1. public class MyThread extends Thread{
  2.     //总金额
  3.     static BigDecimal money = BigDecimal.valueOf(100.0);
  4.     //个数
  5.     static int count = 3;
  6.     //最小抽奖金额
  7.     static final BigDecimal MIN = BigDecimal.valueOf(0.01);
  8.     @Override
  9.     public void run() {
  10.         synchronized (MyThread.class){
  11.             if(count == 0){
  12.                 System.out.println(getName() + "没有抢到红包!");
  13.             }else{
  14.                 //中奖金额
  15.                 BigDecimal prize;
  16.                 if(count == 1){
  17.                     prize = money;
  18.                 }else{
  19.                     //获取抽奖范围
  20.                     double bounds = money.subtract(BigDecimal.valueOf(count-1).multiply(MIN)).doubleValue();
  21.                     Random r = new Random();
  22.                     //抽奖金额
  23.                     prize = BigDecimal.valueOf(r.nextDouble(bounds));
  24.                 }
  25.                 //设置抽中红包,小数点保留两位,四舍五入
  26.                 prize = prize.setScale(2,RoundingMode.HALF_UP);
  27.                 //在总金额中去掉对应的钱
  28.                 money = money.subtract(prize);
  29.                 //红包少了一个
  30.                 count--;
  31.                 //输出红包信息
  32.                 System.out.println(getName() + "抽中了" + prize + "元");
  33.             }
  34.         }
  35.     }
  36. }
  37. public class Test {
  38.     public static void main(String[] args) {
  39.         /*
  40.             微信中的抢红包也用到了多线程。
  41.             假设:100块,分成了3个包,现在有5个人去抢。
  42.             其中,红包是共享数据。
  43.             5个人是5条线程。
  44.             打印结果如下:
  45.                     XXX抢到了XXX元
  46.                     XXX抢到了XXX元
  47.                     XXX抢到了XXX元
  48.                     XXX没抢到
  49.                     XXX没抢到
  50.         */
  51.         MyThread t1 = new MyThread();
  52.         MyThread t2 = new MyThread();
  53.         MyThread t3 = new MyThread();
  54.         MyThread t4 = new MyThread();
  55.         MyThread t5 = new MyThread();
  56.         t1.setName("小A");
  57.         t2.setName("小QQ");
  58.         t3.setName("小哈哈");
  59.         t4.setName("小诗诗");
  60.         t5.setName("小丹丹");
  61.         t1.start();
  62.         t2.start();
  63.         t3.start();
  64.         t4.start();
  65.         t5.start();
  66.     }
  67. }
复制代码
练习五:抽奖箱

需求:
​ 有一个抽奖池,该抽奖池中存放了奖励的金额,该抽奖池中的奖项为 {10,5,20,50,100,200,500,800,2,80,300,700};
创建两个抽奖箱(线程)设置线程名称分别为“抽奖箱1”,“抽奖箱2”
随机从抽奖池中获取奖项元素并打印在控制台上,格式如下:
​ 每次抽出一个奖项就打印一个(随机)
​ 抽奖箱1 又产生了一个 10 元大奖
  1.         抽奖箱1 又产生了一个 100 元大奖
  2.         抽奖箱1 又产生了一个 200 元大奖
  3.         抽奖箱1 又产生了一个 800 元大奖  
复制代码
​ 抽奖箱2 又产生了一个 700 元大奖
  1.          .....
复制代码
  1. public class MyThread extends Thread {
  2.     ArrayList<Integer> list;
  3.     public MyThread(ArrayList<Integer> list) {
  4.         this.list = list;
  5.     }
  6.     @Override
  7.     public void run() {
  8.         //1.循环
  9.         //2.同步代码块
  10.         //3.判断
  11.         //4.判断
  12.         while (true) {
  13.             synchronized (MyThread.class) {
  14.                 if (list.size() == 0) {
  15.                     break;
  16.                 } else {
  17.                     //继续抽奖
  18.                     Collections.shuffle(list);
  19.                     int prize = list.remove(0);
  20.                     System.out.println(getName() + "又产生了一个" + prize + "元大奖");
  21.                 }
  22.             }
  23.             try {
  24.                 Thread.sleep(10);
  25.             } catch (InterruptedException e) {
  26.                 e.printStackTrace();
  27.             }
  28.         }
  29.     }
  30. }
  31. public class Test {
  32.     public static void main(String[] args) {
  33.         /*
  34.             有一个抽奖池,该抽奖池中存放了奖励的金额,该抽奖池中的奖项为 {10,5,20,50,100,200,500,800,2,80,300,700};
  35.             创建两个抽奖箱(线程)设置线程名称分别为“抽奖箱1”,“抽奖箱2”
  36.             随机从抽奖池中获取奖项元素并打印在控制台上,格式如下:
  37.                              每次抽出一个奖项就打印一个(随机)
  38.                     抽奖箱1 又产生了一个 10 元大奖
  39.                     抽奖箱1 又产生了一个 100 元大奖
  40.                     抽奖箱1 又产生了一个 200 元大奖
  41.                     抽奖箱1 又产生了一个 800 元大奖
  42.                     抽奖箱2 又产生了一个 700 元大奖
  43.                     .....
  44.         */
  45.         //创建奖池
  46.         ArrayList<Integer> list = new ArrayList<>();
  47.         Collections.addAll(list,10,5,20,50,100,200,500,800,2,80,300,700);
  48.         //创建线程
  49.         MyThread t1 = new MyThread(list);
  50.         MyThread t2 = new MyThread(list);
  51.         //设置名字
  52.         t1.setName("抽奖箱1");
  53.         t2.setName("抽奖箱2");
  54.         //启动线程
  55.         t1.start();
  56.         t2.start();
  57.     }
  58. }
复制代码
练习六:多线程统计并求最大值

需求:
​ 在上一题基础上继续完成如下需求:
​ 每次抽的过程中,不打印,抽完时一次性打印(随机)
​ 在此次抽奖过程中,抽奖箱1总共产生了6个奖项。
​ 分别为:10,20,100,500,2,300最高奖项为300元,总计额为932元

​ 在此次抽奖过程中,抽奖箱2总共产生了6个奖项。
​ 分别为:5,50,200,800,80,700最高奖项为800元,总计额为1835元

解决方案一:
  1. public class MyThread extends Thread {
  2.     ArrayList<Integer> list;
  3.     public MyThread(ArrayList<Integer> list) {
  4.         this.list = list;
  5.     }
  6.     //线程一
  7.     static ArrayList<Integer> list1 = new ArrayList<>();
  8.     //线程二
  9.     static ArrayList<Integer> list2 = new ArrayList<>();
  10.     @Override
  11.     public void run() {
  12.         while (true) {
  13.             synchronized (MyThread.class) {
  14.                 if (list.size() == 0) {
  15.                     if("抽奖箱1".equals(getName())){
  16.                         System.out.println("抽奖箱1" + list1);
  17.                     }else {
  18.                         System.out.println("抽奖箱2" + list2);
  19.                     }
  20.                     break;
  21.                 } else {
  22.                     //继续抽奖
  23.                     Collections.shuffle(list);
  24.                     int prize = list.remove(0);
  25.                     if("抽奖箱1".equals(getName())){
  26.                         list1.add(prize);
  27.                     }else {
  28.                         list2.add(prize);
  29.                     }
  30.                 }
  31.             }
  32.             try {
  33.                 Thread.sleep(10);
  34.             } catch (InterruptedException e) {
  35.                 e.printStackTrace();
  36.             }
  37.         }
  38.     }
  39. }
  40. public class Test {
  41.     public static void main(String[] args) {
  42.         /*
  43.             有一个抽奖池,该抽奖池中存放了奖励的金额,该抽奖池中的奖项为 {10,5,20,50,100,200,500,800,2,80,300,700};
  44.             创建两个抽奖箱(线程)设置线程名称分别为“抽奖箱1”,“抽奖箱2”
  45.             随机从抽奖池中获取奖项元素并打印在控制台上,格式如下:
  46.             每次抽的过程中,不打印,抽完时一次性打印(随机)    在此次抽奖过程中,抽奖箱1总共产生了6个奖项。
  47.                 分别为:10,20,100,500,2,300最高奖项为300元,总计额为932元
  48.             在此次抽奖过程中,抽奖箱2总共产生了6个奖项。
  49.                 分别为:5,50,200,800,80,700最高奖项为800元,总计额为1835元
  50.         */
  51.         //创建奖池
  52.         ArrayList<Integer> list = new ArrayList<>();
  53.         Collections.addAll(list,10,5,20,50,100,200,500,800,2,80,300,700);
  54.         //创建线程
  55.         MyThread t1 = new MyThread(list);
  56.         MyThread t2 = new MyThread(list);
  57.         //设置名字
  58.         t1.setName("抽奖箱1");
  59.         t2.setName("抽奖箱2");
  60.         //启动线程
  61.         t1.start();
  62.         t2.start();
  63.     }
  64. }
复制代码
解决方案二:
  1. public class MyThread extends Thread {
  2.     ArrayList<Integer> list;
  3.     public MyThread(ArrayList<Integer> list) {
  4.         this.list = list;
  5.     }
  6.     @Override
  7.     public void run() {
  8.         ArrayList<Integer> boxList = new ArrayList<>();//1 //2
  9.         while (true) {
  10.             synchronized (MyThread.class) {
  11.                 if (list.size() == 0) {
  12.                     System.out.println(getName() + boxList);
  13.                     break;
  14.                 } else {
  15.                     //继续抽奖
  16.                     Collections.shuffle(list);
  17.                     int prize = list.remove(0);
  18.                     boxList.add(prize);
  19.                 }
  20.             }
  21.             try {
  22.                 Thread.sleep(10);
  23.             } catch (InterruptedException e) {
  24.                 e.printStackTrace();
  25.             }
  26.         }
  27.     }
  28. }
  29. public class Test {
  30.     public static void main(String[] args) {
  31.         /*
  32.             有一个抽奖池,该抽奖池中存放了奖励的金额,该抽奖池中的奖项为 {10,5,20,50,100,200,500,800,2,80,300,700};
  33.             创建两个抽奖箱(线程)设置线程名称分别为“抽奖箱1”,“抽奖箱2”
  34.             随机从抽奖池中获取奖项元素并打印在控制台上,格式如下:
  35.             每次抽的过程中,不打印,抽完时一次性打印(随机)    在此次抽奖过程中,抽奖箱1总共产生了6个奖项。
  36.                 分别为:10,20,100,500,2,300最高奖项为300元,总计额为932元
  37.             在此次抽奖过程中,抽奖箱2总共产生了6个奖项。
  38.                 分别为:5,50,200,800,80,700最高奖项为800元,总计额为1835元
  39.         */
  40.         //创建奖池
  41.         ArrayList<Integer> list = new ArrayList<>();
  42.         Collections.addAll(list,10,5,20,50,100,200,500,800,2,80,300,700);
  43.         //创建线程
  44.         MyThread t1 = new MyThread(list);
  45.         MyThread t2 = new MyThread(list);
  46.         //设置名字
  47.         t1.setName("抽奖箱1");
  48.         t2.setName("抽奖箱2");
  49.         //启动线程
  50.         t1.start();
  51.         t2.start();
  52.     }
  53. }
复制代码
练习七:多线程之间的比力

需求:
​ 在上一题基础上继续完成如下需求:
​ 在此次抽奖过程中,抽奖箱1总共产生了6个奖项,分别为:10,20,100,500,2,300
  1. 最高奖项为300元,总计额为932元
复制代码
​ 在此次抽奖过程中,抽奖箱2总共产生了6个奖项,分别为:5,50,200,800,80,700
  1. 最高奖项为800元,总计额为1835元
复制代码
​ 在此次抽奖过程中,抽奖箱2中产生了最大奖项,该奖项金额为800元
​ 以上打印效果只是数据模仿,实际代码运行的效果会有差别
  1. public class MyCallable implements Callable<Integer> {    ArrayList<Integer> list;    public MyCallable(ArrayList<Integer> list) {        this.list = list;    }    @Override    public Integer call() throws Exception {        ArrayList<Integer> boxList = new ArrayList<>();//1 //2        while (true) {            synchronized (MyCallable.class) {                if (list.size() == 0) {                    System.out.println(Thread.currentThread().getName() + boxList);                    break;                } else {                    //继续抽奖                    Collections.shuffle(list);                    int prize = list.remove(0);                    boxList.add(prize);                }            }            Thread.sleep(10);        }        //把聚集中的最大值返回        if(boxList.size() == 0){            return null;        }else{            return Collections.max(boxList);        }    }}package com.itheima.test7;import java.util.ArrayList;import java.util.Collections;import java.util.concurrent.ExecutionException;import java.util.concurrent.FutureTask;public class Test {    public static void main(String[] args) throws ExecutionException, InterruptedException {        /*            有一个抽奖池,该抽奖池中存放了奖励的金额,该抽奖池中的奖项为 {10,5,20,50,100,200,500,800,2,80,300,700};            创建两个抽奖箱(线程)设置线程名称分别为    "抽奖箱1", "抽奖箱2"            随机从抽奖池中获取奖项元素并打印在控制台上,格式如下:            在此次抽奖过程中,抽奖箱1总共产生了6个奖项,分别为:10,20,100,500,2,300                    最高奖项为300元,总计额为932元
  2.             在此次抽奖过程中,抽奖箱2总共产生了6个奖项,分别为:5,50,200,800,80,700                    最高奖项为800元,总计额为1835元
  3.             在此次抽奖过程中,抽奖箱2中产生了最大奖项,该奖项金额为800元            焦点逻辑:获取线程抽奖的最大值(看成是线程运行的效果)            以上打印效果只是数据模仿,实际代码运行的效果会有差别        */        //创建奖池        ArrayList<Integer> list = new ArrayList<>();        Collections.addAll(list,10,5,20,50,100,200,500,800,2,80,300,700);        //创建多线程要运行的参数对象        MyCallable mc = new MyCallable(list);        //创建多线程运行效果的管理者对象        //线程一        FutureTask<Integer> ft1 = new FutureTask<>(mc);        //线程二        FutureTask<Integer> ft2 = new FutureTask<>(mc);        //创建线程对象        Thread t1 = new Thread(ft1);        Thread t2 = new Thread(ft2);        //设置名字        t1.setName("抽奖箱1");        t2.setName("抽奖箱2");        //开启线程        t1.start();        t2.start();        Integer max1 = ft1.get();        Integer max2 = ft2.get();        System.out.println(max1);        System.out.println(max2);        //在此次抽奖过程中,抽奖箱2中产生了最大奖项,该奖项金额为800元        if(max1 == null){            System.out.println("在此次抽奖过程中,抽奖箱2中产生了最大奖项,该奖项金额为"+max2+"元");        }else if(max2 == null){            System.out.println("在此次抽奖过程中,抽奖箱1中产生了最大奖项,该奖项金额为"+max1+"元");        }else if(max1 > max2){            System.out.println("在此次抽奖过程中,抽奖箱1中产生了最大奖项,该奖项金额为"+max1+"元");        }else if(max1 < max2){            System.out.println("在此次抽奖过程中,抽奖箱2中产生了最大奖项,该奖项金额为"+max2+"元");        }else{            System.out.println("两者的最大奖项是一样的");        }    }}
复制代码
2. 原子性

2.1 volatile-问题

代码分析 :
  1. package com.itheima.myvolatile;
  2. public class Demo {
  3.     public static void main(String[] args) {
  4.         MyThread1 t1 = new MyThread1();
  5.         t1.setName("小路同学");
  6.         t1.start();
  7.         MyThread2 t2 = new MyThread2();
  8.         t2.setName("小皮同学");
  9.         t2.start();
  10.     }
  11. }
复制代码
  1. package com.itheima.myvolatile;
  2. public class Money {
  3.     public static int money = 100000;
  4. }
复制代码
  1. package com.itheima.myvolatile;
  2. public class MyThread1 extends  Thread {
  3.     @Override
  4.     public void run() {
  5.         while(Money.money == 100000){
  6.         }
  7.         System.out.println("结婚基金已经不是十万了");
  8.     }
  9. }
复制代码
  1. package com.itheima.myvolatile;
  2. public class MyThread2 extends Thread {
  3.     @Override
  4.     public void run() {
  5.         try {
  6.             Thread.sleep(10);
  7.         } catch (InterruptedException e) {
  8.             e.printStackTrace();
  9.         }
  10.         Money.money = 90000;
  11.     }
  12. }
复制代码
程序问题 : 女孩固然知道结婚基金是十万,但是当基金的余额发生变化的时候,女孩无法知道最新的余额。
2.2 volatile解决

以上案例出现的问题 :
​ 当A线程修改了共享数据时,B线程没有及时获取到最新的值,如果还在使用原先的值,就会出现问题
​ 1,堆内存是唯一的,每一个线程都有自己的线程栈。
​ 2 ,每一个线程在使用堆内里变量的时候,都会先拷贝一份到变量的副本中。
​ 3 ,在线程中,每一次使用是从变量的副本中获取的。
Volatile关键字 : 强制线程每次在使用的时候,都会看一下共享区域最新的值
代码实现 : 使用volatile关键字解决
  1. package com.itheima.myvolatile;
  2. public class Demo {
  3.     public static void main(String[] args) {
  4.         MyThread1 t1 = new MyThread1();
  5.         t1.setName("小路同学");
  6.         t1.start();
  7.         MyThread2 t2 = new MyThread2();
  8.         t2.setName("小皮同学");
  9.         t2.start();
  10.     }
  11. }
复制代码
  1. package com.itheima.myvolatile;
  2. public class Money {
  3.     public static volatile int money = 100000;
  4. }
复制代码
  1. package com.itheima.myvolatile;
  2. public class MyThread1 extends  Thread {
  3.     @Override
  4.     public void run() {
  5.         while(Money.money == 100000){
  6.         }
  7.         System.out.println("结婚基金已经不是十万了");
  8.     }
  9. }
复制代码
  1. package com.itheima.myvolatile;
  2. public class MyThread2 extends Thread {
  3.     @Override
  4.     public void run() {
  5.         try {
  6.             Thread.sleep(10);
  7.         } catch (InterruptedException e) {
  8.             e.printStackTrace();
  9.         }
  10.         Money.money = 90000;
  11.     }
  12. }
复制代码
2.3 synchronized解决

synchronized解决 :
​ 1 ,线程获得锁
​ 2 ,清空变量副本
​ 3 ,拷贝共享变量最新的值到变量副本中
​ 4 ,执行代码
​ 5 ,将修改后变量副本中的值赋值给共享数据
​ 6 ,释放锁
代码实现 :
  1. package com.itheima.myvolatile2;
  2. public class Demo {
  3.     public static void main(String[] args) {
  4.         MyThread1 t1 = new MyThread1();
  5.         t1.setName("小路同学");
  6.         t1.start();
  7.         MyThread2 t2 = new MyThread2();
  8.         t2.setName("小皮同学");
  9.         t2.start();
  10.     }
  11. }
复制代码
  1. package com.itheima.myvolatile2;
  2. public class Money {
  3.     public static Object lock = new Object();
  4.     public static volatile int money = 100000;
  5. }
复制代码
  1. package com.itheima.myvolatile2;
  2. public class MyThread1 extends  Thread {
  3.     @Override
  4.     public void run() {
  5.         while(true){
  6.             synchronized (Money.lock){
  7.                 if(Money.money != 100000){
  8.                     System.out.println("结婚基金已经不是十万了");
  9.                     break;
  10.                 }
  11.             }
  12.         }
  13.     }
  14. }
复制代码
  1. package com.itheima.myvolatile2;
  2. public class MyThread2 extends Thread {
  3.     @Override
  4.     public void run() {
  5.         synchronized (Money.lock) {
  6.             try {
  7.                 Thread.sleep(10);
  8.             } catch (InterruptedException e) {
  9.                 e.printStackTrace();
  10.             }
  11.             Money.money = 90000;
  12.         }
  13.     }
  14. }
复制代码
2.4 原子性

概述 : 所谓的原子性是指在一次操作大概多次操作中,要么所有的操作全部都得到了执行而且不会受到任何因素的干扰而停止,要么所有的操作都不执行,多个操作是一个不可以分割的整体。
代码实现 :
  1. package com.itheima.threadatom;
  2. public class AtomDemo {
  3.     public static void main(String[] args) {
  4.         MyAtomThread atom = new MyAtomThread();
  5.         for (int i = 0; i < 100; i++) {
  6.             new Thread(atom).start();
  7.         }
  8.     }
  9. }
  10. class MyAtomThread implements Runnable {
  11.     private volatile int count = 0; //送冰淇淋的数量
  12.     @Override
  13.     public void run() {
  14.         for (int i = 0; i < 100; i++) {
  15.             //1,从共享数据中读取数据到本线程栈中.
  16.             //2,修改本线程栈中变量副本的值
  17.             //3,会把本线程栈中变量副本的值赋值给共享数据.
  18.             count++;
  19.             System.out.println("已经送了" + count + "个冰淇淋");
  20.         }
  21.     }
  22. }
复制代码
代码总结 : count++ 不是一个原子性操作, 他在执行的过程中,有可能被其他线程打断
2.5 volatile关键字不能保证原子性

解决方案 : 我们可以给count++操作添加锁,那么count++操作就是临界区中的代码,临界区中的代码一次只能被一个线程去执行,以是count++就酿成了原子操作。
  1. package com.itheima.threadatom2;
  2. public class AtomDemo {
  3.     public static void main(String[] args) {
  4.         MyAtomThread atom = new MyAtomThread();
  5.         for (int i = 0; i < 100; i++) {
  6.             new Thread(atom).start();
  7.         }
  8.     }
  9. }
  10. class MyAtomThread implements Runnable {
  11.     private volatile int count = 0; //送冰淇淋的数量
  12.     private Object lock = new Object();
  13.     @Override
  14.     public void run() {
  15.         for (int i = 0; i < 100; i++) {
  16.             //1,从共享数据中读取数据到本线程栈中.
  17.             //2,修改本线程栈中变量副本的值
  18.             //3,会把本线程栈中变量副本的值赋值给共享数据.
  19.             synchronized (lock) {
  20.                 count++;
  21.                 System.out.println("已经送了" + count + "个冰淇淋");
  22.             }
  23.         }
  24.     }
  25. }
复制代码
2.6 原子性_AtomicInteger

概述:java从JDK1.5开始提供了java.util.concurrent.atomic包(简称Atomic包),这个包中的原子操作类提供了一种用法简单,性能高效,线程安全地更新一个变量的方式。因为变
量的类型有许多种,以是在Atomic包里一共提供了13个类,属于4种类型的原子更新方式,分别是原子更新根本类型、原子更新数组、原子更新引用和原子更新属性(字段)。本次我们只解说
使用原子的方式更新根本类型,使用原子的方式更新根本类型Atomic包提供了以下3个类:
AtomicBoolean: 原子更新布尔类型
AtomicInteger: 原子更新整型
AtomicLong: 原子更新长整型
以上3个类提供的方法险些一模一样,以是本节仅以AtomicInteger为例进行解说,AtomicInteger的常用方法如下:
  1. public AtomicInteger():                                       初始化一个默认值为0的原子型Integer
  2. public AtomicInteger(int initialValue):  初始化一个指定值的原子型Integer
  3. int get():                                                            获取值
  4. int getAndIncrement():                               以原子方式将当前值加1,注意,这里返回的是自增前的值。
  5. int incrementAndGet():                                      以原子方式将当前值加1,注意,这里返回的是自增后的值。
  6. int addAndGet(int data):                                 以原子方式将输入的数值与实例中的值(AtomicInteger里的value)相加,并返回结果。
  7. int getAndSet(int value):                            以原子方式设置为newValue的值,并返回旧值。
复制代码
代码实现 :
  1. package com.itheima.threadatom3;
  2. import java.util.concurrent.atomic.AtomicInteger;
  3. public class MyAtomIntergerDemo1 {
  4. //    public AtomicInteger():                       初始化一个默认值为0的原子型Integer
  5. //    public AtomicInteger(int initialValue): 初始化一个指定值的原子型Integer
  6.     public static void main(String[] args) {
  7.         AtomicInteger ac = new AtomicInteger();
  8.         System.out.println(ac);
  9.         AtomicInteger ac2 = new AtomicInteger(10);
  10.         System.out.println(ac2);
  11.     }
  12. }
复制代码
  1. package com.itheima.threadatom3;
  2. import java.lang.reflect.Field;
  3. import java.util.concurrent.atomic.AtomicInteger;
  4. public class MyAtomIntergerDemo2 {
  5. //    int get():                                    获取值
  6. //    int getAndIncrement():     以原子方式将当前值加1,注意,这里返回的是自增前的值。
  7. //    int incrementAndGet():     以原子方式将当前值加1,注意,这里返回的是自增后的值。
  8. //    int addAndGet(int data):         以原子方式将参数与对象中的值相加,并返回结果。
  9. //    int getAndSet(int value):  以原子方式设置为newValue的值,并返回旧值。
  10.     public static void main(String[] args) {
  11. //        AtomicInteger ac1 = new AtomicInteger(10);
  12. //        System.out.println(ac1.get());
  13. //        AtomicInteger ac2 = new AtomicInteger(10);
  14. //        int andIncrement = ac2.getAndIncrement();
  15. //        System.out.println(andIncrement);
  16. //        System.out.println(ac2.get());
  17. //        AtomicInteger ac3 = new AtomicInteger(10);
  18. //        int i = ac3.incrementAndGet();
  19. //        System.out.println(i);//自增后的值
  20. //        System.out.println(ac3.get());
  21. //        AtomicInteger ac4 = new AtomicInteger(10);
  22. //        int i = ac4.addAndGet(20);
  23. //        System.out.println(i);
  24. //        System.out.println(ac4.get());
  25.         AtomicInteger ac5 = new AtomicInteger(100);
  26.         int andSet = ac5.getAndSet(20);
  27.         System.out.println(andSet);
  28.         System.out.println(ac5.get());
  29.     }
  30. }
复制代码
2.7 AtomicInteger-内存解析

AtomicInteger原理 : 自旋锁 + CAS 算法
CAS算法:
​ 有3个操作数(内存值V, 旧的预期值A,要修改的值B)
​ 当旧的预期值A == 内存值 此时修改成功,将V改为B
​ 当旧的预期值A!=内存值 此时修改失败,不做任何操作
​ 并重新获取如今的最新值(这个重新获取的动作就是自旋)
2.8 AtomicInteger-源码解析

代码实现 :
  1. package com.itheima.threadatom4;
  2. public class AtomDemo {
  3.     public static void main(String[] args) {
  4.         MyAtomThread atom = new MyAtomThread();
  5.         for (int i = 0; i < 100; i++) {
  6.             new Thread(atom).start();
  7.         }
  8.     }
  9. }
复制代码
  1. package com.itheima.threadatom4;
  2. import java.util.concurrent.atomic.AtomicInteger;
  3. public class MyAtomThread implements Runnable {
  4.     //private volatile int count = 0; //送冰淇淋的数量
  5.     //private Object lock = new Object();
  6.     AtomicInteger ac = new AtomicInteger(0);
  7.     @Override
  8.     public void run() {
  9.         for (int i = 0; i < 100; i++) {
  10.             //1,从共享数据中读取数据到本线程栈中.
  11.             //2,修改本线程栈中变量副本的值
  12.             //3,会把本线程栈中变量副本的值赋值给共享数据.
  13.             //synchronized (lock) {
  14. //                count++;
  15. //                ac++;
  16.             int count = ac.incrementAndGet();
  17.             System.out.println("已经送了" + count + "个冰淇淋");
  18.            // }
  19.         }
  20.     }
  21. }
复制代码
源码解析 :
  1. //先自增,然后获取自增后的结果
  2. public final int incrementAndGet() {
  3.         //+ 1 自增后的结果
  4.         //this 就表示当前的atomicInteger(值)
  5.         //1    自增一次
  6.         return U.getAndAddInt(this, VALUE, 1) + 1;
  7. }
  8. public final int getAndAddInt(Object o, long offset, int delta) {
  9.         //v 旧值
  10.         int v;
  11.         //自旋的过程
  12.         do {
  13.             //不断的获取旧值
  14.             v = getIntVolatile(o, offset);
  15.             //如果这个方法的返回值为false,那么继续自旋
  16.             //如果这个方法的返回值为true,那么自旋结束
  17.             //o 表示的就是内存值
  18.             //v 旧值
  19.             //v + delta 修改后的值
  20.         } while (!weakCompareAndSetInt(o, offset, v, v + delta));
  21.             //作用:比较内存中的值,旧值是否相等,如果相等就把修改后的值写到内存中,返回true。表示修改成功。
  22.             //                                 如果不相等,无法把修改后的值写到内存中,返回false。表示修改失败。
  23.             //如果修改失败,那么继续自旋。
  24.         return v;
  25. }
复制代码
2.9 悲观锁和乐观锁

synchronized和CAS的区别 :
**相同点:**在多线程环境下,都可以保证共享数据的安全性。
**差别点:**synchronized总是从最坏的角度出发,认为每次获取数据的时候,别人都有可能修改。以是在每 次操作共享数据之前,都会上锁。(悲观锁)
​ cas是从乐观的角度出发,假设每次获取数据别人都不会修改,以是不会上锁。只不外在修改共享数据的时候,会检查一下,别人有没有修改过这个数据。
​ 如果别人修改过,那么我再次获取如今最新的值。
​ 如果别人没有修改过,那么我如今直接修改共享数据的值.(乐观锁)
3. 并发工具类

3.1 并发工具类-Hashtable

Hashtable出现的原因 : 在聚集类中HashMap是比力常用的聚集对象,但是HashMap是线程不安全的(多线程环境下可能会存在问题)。为了保证数据的安全性我们可以使用Hashtable,但是Hashtable的效率低下。
代码实现 :
  1. package com.itheima.mymap;
  2. import java.util.HashMap;
  3. import java.util.Hashtable;
  4. public class MyHashtableDemo {
  5.     public static void main(String[] args) throws InterruptedException {
  6.         Hashtable<String, String> hm = new Hashtable<>();
  7.         Thread t1 = new Thread(() -> {
  8.             for (int i = 0; i < 25; i++) {
  9.                 hm.put(i + "", i + "");
  10.             }
  11.         });
  12.         Thread t2 = new Thread(() -> {
  13.             for (int i = 25; i < 51; i++) {
  14.                 hm.put(i + "", i + "");
  15.             }
  16.         });
  17.         t1.start();
  18.         t2.start();
  19.         System.out.println("----------------------------");
  20.         //为了t1和t2能把数据全部添加完毕
  21.         Thread.sleep(1000);
  22.         //0-0 1-1 ..... 50- 50
  23.         for (int i = 0; i < 51; i++) {
  24.             System.out.println(hm.get(i + ""));
  25.         }//0 1 2 3 .... 50
  26.     }
  27. }
复制代码
3.2 并发工具类-ConcurrentHashMap根本使用

ConcurrentHashMap出现的原因 : 在聚集类中HashMap是比力常用的聚集对象,但是HashMap是线程不安全的(多线程环境下可能会存在问题)。为了保证数据的安全性我们可以使用Hashtable,但是Hashtable的效率低下。
基于以上两个原因我们可以使用JDK1.5以后所提供的ConcurrentHashMap。
体系结构 :

总结 :
​ 1 ,HashMap是线程不安全的。多线程环境下会有数据安全问题
​ 2 ,Hashtable是线程安全的,但是会将整张表锁起来,效率低下
​ 3,ConcurrentHashMap也是线程安全的,效率较高。 在JDK7和JDK8中,底层原理不一样。
代码实现 :
  1. package com.itheima.mymap;
  2. import java.util.Hashtable;
  3. import java.util.concurrent.ConcurrentHashMap;
  4. public class MyConcurrentHashMapDemo {
  5.     public static void main(String[] args) throws InterruptedException {
  6.         ConcurrentHashMap<String, String> hm = new ConcurrentHashMap<>(100);
  7.         Thread t1 = new Thread(() -> {
  8.             for (int i = 0; i < 25; i++) {
  9.                 hm.put(i + "", i + "");
  10.             }
  11.         });
  12.         Thread t2 = new Thread(() -> {
  13.             for (int i = 25; i < 51; i++) {
  14.                 hm.put(i + "", i + "");
  15.             }
  16.         });
  17.         t1.start();
  18.         t2.start();
  19.         System.out.println("----------------------------");
  20.         //为了t1和t2能把数据全部添加完毕
  21.         Thread.sleep(1000);
  22.         //0-0 1-1 ..... 50- 50
  23.         for (int i = 0; i < 51; i++) {
  24.             System.out.println(hm.get(i + ""));
  25.         }//0 1 2 3 .... 50
  26.     }
  27. }
复制代码
3.3 并发工具类-ConcurrentHashMap1.7原理


3.4 并发工具类-ConcurrentHashMap1.8原理


总结 :
​ 1,如果使用空参构造创建ConcurrentHashMap对象,则什么事情都不做。 在第一次添加元素的时候创建哈希表
​ 2,计算当前元素应存入的索引。
​ 3,如果该索引位置为null,则利用cas算法,将本结点添加到数组中。
​ 4,如果该索引位置不为null,则利用volatile关键字获得当前位置最新的结点地址,挂在他下面,酿成链表。
​ 5,当链表的长度大于等于8时,自动转换成红黑树6,以链表大概红黑树头结点为锁对象,配合悲观锁保证多线程操作集适时数据的安全性
3.5 并发工具类-CountDownLatch

CountDownLatch类 :
方法解释public CountDownLatch(int count)参数传递线程数,表示等待线程数目public void await()让线程等待public void countDown()当前线程执行完毕 使用场景: 让某一条线程等待其他线程执行完毕之后再执行
代码实现 :
  1. package com.itheima.mycountdownlatch;
  2. import java.util.concurrent.CountDownLatch;
  3. public class ChileThread1 extends Thread {
  4.     private CountDownLatch countDownLatch;
  5.     public ChileThread1(CountDownLatch countDownLatch) {
  6.         this.countDownLatch = countDownLatch;
  7.     }
  8.     @Override
  9.     public void run() {
  10.         //1.吃饺子
  11.         for (int i = 1; i <= 10; i++) {
  12.             System.out.println(getName() + "在吃第" + i + "个饺子");
  13.         }
  14.         //2.吃完说一声
  15.         //每一次countDown方法的时候,就让计数器-1
  16.         countDownLatch.countDown();
  17.     }
  18. }
复制代码
  1. package com.itheima.mycountdownlatch;
  2. import java.util.concurrent.CountDownLatch;
  3. public class ChileThread2 extends Thread {
  4.     private CountDownLatch countDownLatch;
  5.     public ChileThread2(CountDownLatch countDownLatch) {
  6.         this.countDownLatch = countDownLatch;
  7.     }
  8.     @Override
  9.     public void run() {
  10.         //1.吃饺子
  11.         for (int i = 1; i <= 15; i++) {
  12.             System.out.println(getName() + "在吃第" + i + "个饺子");
  13.         }
  14.         //2.吃完说一声
  15.         //每一次countDown方法的时候,就让计数器-1
  16.         countDownLatch.countDown();
  17.     }
  18. }
复制代码
  1. package com.itheima.mycountdownlatch;
  2. import java.util.concurrent.CountDownLatch;
  3. public class ChileThread3 extends Thread {
  4.     private CountDownLatch countDownLatch;
  5.     public ChileThread3(CountDownLatch countDownLatch) {
  6.         this.countDownLatch = countDownLatch;
  7.     }
  8.     @Override
  9.     public void run() {
  10.         //1.吃饺子
  11.         for (int i = 1; i <= 20; i++) {
  12.             System.out.println(getName() + "在吃第" + i + "个饺子");
  13.         }
  14.         //2.吃完说一声
  15.         //每一次countDown方法的时候,就让计数器-1
  16.         countDownLatch.countDown();
  17.     }
  18. }
复制代码
  1. package com.itheima.mycountdownlatch;
  2. import java.util.concurrent.CountDownLatch;
  3. public class MotherThread extends Thread {
  4.     private CountDownLatch countDownLatch;
  5.     public MotherThread(CountDownLatch countDownLatch) {
  6.         this.countDownLatch = countDownLatch;
  7.     }
  8.     @Override
  9.     public void run() {
  10.         //1.等待
  11.         try {
  12.             //当计数器变成0的时候,会自动唤醒这里等待的线程。
  13.             countDownLatch.await();
  14.         } catch (InterruptedException e) {
  15.             e.printStackTrace();
  16.         }
  17.         //2.收拾碗筷
  18.         System.out.println("妈妈在收拾碗筷");
  19.     }
  20. }
复制代码
  1. package com.itheima.mycountdownlatch;
  2. import java.util.concurrent.CountDownLatch;
  3. public class MyCountDownLatchDemo {
  4.     public static void main(String[] args) {
  5.         //1.创建CountDownLatch的对象,需要传递给四个线程。
  6.         //在底层就定义了一个计数器,此时计数器的值就是3
  7.         CountDownLatch countDownLatch = new CountDownLatch(3);
  8.         //2.创建四个线程对象并开启他们。
  9.         MotherThread motherThread = new MotherThread(countDownLatch);
  10.         motherThread.start();
  11.         ChileThread1 t1 = new ChileThread1(countDownLatch);
  12.         t1.setName("小明");
  13.         ChileThread2 t2 = new ChileThread2(countDownLatch);
  14.         t2.setName("小红");
  15.         ChileThread3 t3 = new ChileThread3(countDownLatch);
  16.         t3.setName("小刚");
  17.         t1.start();
  18.         t2.start();
  19.         t3.start();
  20.     }
  21. }
复制代码
总结 :
​ 1. CountDownLatch(int count):参数写等待线程的数目。并定义了一个计数器。
​ 2. await():让线程等待,当计数器为0时,会唤醒等待的线程
​ 3. countDown(): 线程执行完毕时调用,会将计数器-1。
3.6 并发工具类-Semaphore

使用场景 :
​ 可以控制访问特定资源的线程数目。
实现步调 :
​ 1,必要有人管理这个通道
​ 2,当有车进来了,发通行许可证
​ 3,当车出去了,收回通行许可证
​ 4,如果通行许可证发完了,那么其他车辆只能等着
代码实现 :
  1. package com.itheima.mysemaphore;
  2. import java.util.concurrent.Semaphore;
  3. public class MyRunnable implements Runnable {
  4.     //1.获得管理员对象,
  5.     private Semaphore semaphore = new Semaphore(2);
  6.     @Override
  7.     public void run() {
  8.         //2.获得通行证
  9.         try {
  10.             semaphore.acquire();
  11.             //3.开始行驶
  12.             System.out.println("获得了通行证开始行驶");
  13.             Thread.sleep(2000);
  14.             System.out.println("归还通行证");
  15.             //4.归还通行证
  16.             semaphore.release();
  17.         } catch (InterruptedException e) {
  18.             e.printStackTrace();
  19.         }
  20.     }
  21. }
复制代码
  1. package com.itheima.mysemaphore;
  2. public class MySemaphoreDemo {
  3.     public static void main(String[] args) {
  4.         MyRunnable mr = new MyRunnable();
  5.         for (int i = 0; i < 100; i++) {
  6.             new Thread(mr).start();
  7.         }
  8.     }
  9. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

梦应逍遥

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表