• 多线程


    1.  程序和进程

    程序就是一堆静态的代码,存储在硬盘上。程序如果不运行,本质就是一个文件。

    程序一次运行产生进程,进程一直向前运行,直到进程结束。

    2.操作系统的发展

    单任务操作系统:一段时间只能运行一个程序(任务)。CPU利用率非常低。

    |

    |/

    引入进程的概念

    把程序的一次运行产生进程(内存空间、资源、程序的执行堆栈)

    进程作为操作系统分配资源的基本单位。

    |

    |/

    多任务操作系统

    一台电脑就一个CPU,多个任务轮流使用CPU,从宏观上看,一段时间有多个任务正在运行。

    从微观上看,一个时间点只有一个任务在运行。

    CPU时间片

    多个进程通过CPU时间片轮转实现多任务(进程)。把这种现象叫做并发操作

    并行:

    多个CPU运行各自的进行。

    |

    |/

    线程的引入

    解决实时性问题

    3. 进程和线程区别

     

    4.  多线程实现

    Thread类位于java.lang中,表示进程中的执行线程。实现多线程有两种方式

    1)继承Thread

     1 public class MyThread extends Thread {
     2 
     3  
     4 
     5      @Override
     6 
     7      publicvoid run() {
     8 
     9          System.out.println("我是多线程MyThread");
    10 
    11          for (inti = 0; i< 5; i++) {
    12 
    13               System.out.println("MyThread:" + i);
    14 
    15          }
    16 
    17      }
    18 
    19 }
     1 publicclass Test01 {
     2 
     3      publicstaticvoid main(String[] args) {
     4 
     5  
     6 
     7          // main开始运行产生一个进程,该进程默认有个主(main)线程
     8 
     9          // 创建线程
    10 
    11          MyThread t1 = new MyThread();
    12 
    13          // 启动线程
    14 
    15          t1.start();
    16 
    17  
    18 
    19          for (inti = 0; i< 5; i++) {
    20 
    21               System.out.println("main Thread:" + i);
    22 
    23          }
    24 
    25  
    26 
    27      }
    28 
    29 }

    注:main线程和t1线程抢占CPU执行。多线程在提高CPU利用率的同时,增加程序的复杂度。

    2)实现Runnable接口

     1 public class MyRun implements Runnable {
     2 
     3  
     4 
     5      @Override
     6 
     7      publicvoid run() {
     8 
     9          System.out.println("我是MyRun");
    10 
    11          for (inti = 0; i< 5; i++) {
    12 
    13               System.out.println("my run:" + i);
    14 
    15          }
    16 
    17      }
    18 
    19 }
     1 publicclass Test02 {
     2 
     3      publicstaticvoid main(String[] args) {
     4 
     5         
     6 
     7          MyRun run = new MyRun();
     8 
     9          Thread t1 = new Thread(run);
    10 
    11          t1.start();
    12 
    13  
    14 
    15          // main开始运行产生一个进程,该进程默认有个主(main)线程
    16 
    17          for (inti = 0; i< 5; i++) {
    18 
    19               System.out.println("main Thread:" + i);
    20 
    21          }
    22 
    23      }
    24 
    25 }

    卖票案例

    继承Thread和实现Runnable接口实现多线程的优缺点

    [1]继承Thread的线程类不能再继承其他类,实现Runnable接口的类还可以继承其他类。

    [2]实现Runnable接口的线程类,可以让多个线程共享线程实现类的资源

    总结:

    多线程提高了cpu利用率,但程序的复杂度也随之增加。一旦线程开始执行,很难通过其他方式控制线程的轨迹。

    多个线程抢占CPU导致线程的运行轨迹不确定。

    分析运行轨迹(不同步)

    窗口A卖出一张票,还剩4张票

    窗口B卖出一张票,还剩3张票

    窗口B卖出一张票,还剩0张票

    窗口C卖出一张票,还剩1张票

    窗口A卖出一张票,还剩2张票

    窗口A抢占到CPU,执行run,count=5

    publicvoid run() {

               // 模拟一个窗口5个人

               for (inti = 0; i< 5; i++) {

                     if (count> 0) {

                          count--;

                          System.out.println(Thread.currentThread().getName()+"卖出一张票,还剩" + count + "张票");

                     }

               }

          }

    窗口B抢占到CPU,count=4,执行run

    publicvoid run() {

               // 模拟一个窗口5个人

               for (inti = 0; i< 5; i++) {

                     if (count> 0) {

                          count--;

                          System.out.println(Thread.currentThread().getName()+"卖出一张票,还剩" + count + "张票");

                     }

               }

          }

    窗口A到抢占CPU,count=3,执行run

    publicvoid run() {

               // 模拟一个窗口5个人

               for (inti = 0; i< 5; i++) {

                     if (count> 0) {

                          count--;=> count=2

                          System.out.println(Thread.currentThread().getName()+"卖出一张票,还剩" + count + "张票");  (窗口A在此挂起。count=>2     准备输出的字符串:窗口A卖出一张票,还剩2张)

                     }

               }

          }

    窗口C到抢占CPU,count=2,执行run

    publicvoid run() {

               // 模拟一个窗口5个人

               for (inti = 0; i< 5; i++) {

                     if (count> 0) {

                          count--;=>  count=1

                          System.out.println(Thread.currentThread().getName()+"卖出一张票,还剩" + count + "张票");(窗口C挂起,count=1       准备输出的字符串:窗口C卖出一张票,还剩1张)

                     }

               }

          }

    窗口B抢占CPU,count=1,从上次挂起的位置开始执行run

    publicvoid run() {

               // 模拟一个窗口5个人

               for (inti = 0; i< 5; i++) {

                     if (count> 0) {

                          count--;

                          System.out.println(Thread.currentThread().getName()+"卖出一张票,还剩" + count + "张票");=> count=0    (窗口B挂起,count=0)

                     }

               }

          }

    窗口C抢占到CPU,count=0,从上次挂起位置开始执行run

    publicvoid run() {

               // 模拟一个窗口5个人

               for (inti = 0; i< 5; i++) {

                     if (count> 0) {

                          count--; =>  count=1   窗口C从此次开始执行,count=1(挂起时)

                          System.out.println(Thread.currentThread().getName()+"卖出一张票,还剩" + count + "张票");

                     }

               }

          }

    窗口A抢占到CPU,count=0,从上次挂起的位置开始执行run

    publicvoid run() {

               // 模拟一个窗口5个人

               for (inti = 0; i< 5; i++) {

                     if (count> 0) {

                          count--; =>count=2   窗口A在此继续执行。count=>2(挂起时)

                          System.out.println(Thread.currentThread().getName()+"卖出一张票,还剩" + count + "张票");

                     }

               }

          }

    结论

    [1]多线程抢占CPU执行,可能在任意位置被切换出去(挂起 )。

    [2]多线程抢占到CPU后,从上次挂起的位置开始执行(先恢复上次的执行堆栈)。

    [3]多线程都可以独立运行,相互不干扰,多个线程都可以能访问共享资源,很容易导致数据错乱!!!

    5. 线程的生命周期

    新生状态

    用new关键字建立一个线程后,该线程对象就处于新生状态。

    处于新生状态的线程有自己的内存空间,通过调用start()方法进入就绪状态。

    就绪状态

    处于就绪状态线程具备了运行条件,但还没分配到CPU,处于线程就绪队列,等待系统为其分配CPU。

    当系统选定一个等待执行的线程后,它就会从就绪状态进入执行状态,该动作称为“CPU调度”。

    运行状态

    在运行状态的线程执行自己的run方法中代码,直到等待某资源而阻塞或完成任何而死亡。

    如果在给定的时间片内没有执行结束,就会被系统给换下来回到等待执行状态。

    阻塞状态

    处于运行状态的线程在某些情况下,如执行了sleep(睡眠)方法,或等待I/O设备等资源,将让出CPU并暂时停止自己运行,进入阻塞状态。

    在阻塞状态的线程不能进入就绪队列。只有当引起阻塞的原因消除时,如睡眠时间已到,或等待的I/O设备空闲下来,线程便转入就绪状态,重新到就绪队列中排队等待,被系统选中后从原来停止的位置开始继续执行。

    死亡状态

    死亡状态是线程生命周期中的最后一个阶段。线程死亡的原因有三个,一个是正常运行

    的线程完成了它的全部工作;另一个是线程被强制性地终止,如通过stop方法来终止一个

    线程【不推荐使用】;三是线程抛出未捕获的异常。

    6.  线程常用方法

    1)线程优先级

     1 public static void main(String[] args) {
     2 
     3         
     4 
     5          System.out.println(Thread.MIN_PRIORITY);
     6 
     7          System.out.println(Thread.MAX_PRIORITY);
     8 
     9          System.out.println(Thread.NORM_PRIORITY);
    10 
    11         
    12 
    13          //主线程的优先级(默认优先级)
    14 
    15          System.out.println(Thread.currentThread().getPriority());
    16 
    17         
    18 
    19         
    20 
    21          Thread01 t1 = new Thread01();
    22 
    23          // 设置线程的优先级
    24 
    25          t1.setPriority(Thread.MAX_PRIORITY);
    26 
    27          t1.start();
    28 
    29         
    30 
    31         
    32 
    33          Thread01 t2 = new Thread01();
    34 
    35          // 设置线程的优先级
    36 
    37          t2.setPriority(Thread.MIN_PRIORITY);
    38 
    39          t2.start();
    40 
    41         
    42 
    43         
    44 
    45      }

    线程优先级高,被cpu调度的概率大,不表示一定先运行。

    2)isAlive

    判断线程是否处于活动状态。

     1  Thread01 t1 = new Thread01();
     2 
     3          System.out.println(t1.isAlive());
     4 
     5          // 设置线程的优先级
     6 
     7          t1.setPriority(Thread.MAX_PRIORITY);
     8 
     9          t1.start();
    10 
    11          System.out.println(t1.isAlive());

    线程调用start之后就处于活动状态。

     3).join

    调用该方法的线程强制执行,其它线程处于阻塞状态,该线程执行完毕后,其它线程再执行

    join称为线程的强制执行,有可能被外界中断产生InterruptedException 中断异常。

     1 public class Test02 {
     2 
     3      publicstaticvoid main(String[] args){
     4 
     5         
     6 
     7          Thread02 t = new Thread02("线程A");
     8 
     9          t.start();
    10 
    11         
    12 
    13          for (inti = 0; i< 5; i++) {
    14 
    15              
    16 
    17               if(i == 2) {
    18 
    19                    try {
    20 
    21                        t.join();
    22 
    23                    } catch (InterruptedException e) {
    24 
    25                        e.printStackTrace();
    26 
    27                    }
    28 
    29               }
    30 
    31              
    32 
    33               System.out.println(Thread.currentThread().getName() + "->" + i);
    34 
    35          }
    36 
    37      }
    38 
    39 }

    4).sleep()

    在指定的毫秒数内让当前正在执行的线程休眠(暂停执行)。休眠的线程进入阻塞状态。

     1 public static void main(String[] args) {
     2 
     3        
     4 
     5         Thread03 t = new Thread03("线程A");
     6 
     7         t.start();
     8 
     9        
    10 
    11         Thread mainThread = Thread.currentThread();
    12 
    13         System.out.println(mainThread.getName()+"即将进入休眠");
    14 
    15         try {
    16 
    17             Thread.sleep(5000);
    18 
    19         } catch (InterruptedException e) {
    20 
    21             e.printStackTrace();
    22 
    23         }
    24 
    25        
    26 
    27         // 中断线程
    28 
    29         t.interrupt();
    30 
    31        
    32 
    33         System.out.println(mainThread.getName()+"休眠完成");
    34 
    35     }

    5).yield()

     1 public static void main(String[] args) {
     2 
     3  
     4 
     5          Thread mainThread = Thread.currentThread();
     6 
     7  
     8 
     9          Thread04 t = new Thread04("线程A");
    10 
    11          t.start();
    12 
    13 
    14          for (inti = 0; i< 5; i++) {
    15 
    16               if (i == 2) {
    17 
    18                    // yield 使当前礼让一次
    19 
    20                    Thread.yield();
    21 
    22               }
    23 
    24               System.out.println(mainThread.getName() + "->" + i);
    25 
    26          }
    27 
    28      }

    A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.

     当前线程给cpu调度器一个暗示,暗示其想礼让一次其拥有的cpu,CPU调度者也可以忽视这次暗示。此时当前线程进入就绪状态。

    6).线程的终止

    目前而言,不推荐使用stop直接终止线程。用interrupt()方法去中断正在执行的线程,而在线程内部一定要写捕获中断的异常。通过异常处理机制正常结束线程。

    7.线程的安全问题(线程同步)

    线程在执行过程中,通过cpu的调度,执行轨迹不确定,对共享资源的访问很容易造成数据的错乱。我们称这个错乱称为线程安全问题。

    1)  同步概念

    原子性操作:一个操作要么一次性做完,要么根本不开始,不存在中间状态。

    案例:ATM取现操作

    同步就是让操作保持原子性!java提供两种方式实现同步。

    2)  同步代码块

    把所有的同步操作放到同步代码块中,

    synchronized (mutex) {

    // .. .

    }

    mutex 称为互斥锁/同步锁。对共享资源进行加锁实现同步。一般用共享资源作为同步锁,也称同步监视器。

     1 public class MyRun implements Runnable {
     2 
     3     
     4 
     5      // 共享资源
     6 
     7      privateintcount = 5;
     8 
     9  
    10 
    11      @Override
    12 
    13      publicvoid run() {
    14 
    15          // 模拟一个窗口5个人
    16 
    17          for (inti = 0; i< 5; i++) {
    18 
    19               // 同步代码块
    20 
    21               // mutex互斥锁
    22 
    23               synchronized (this) {
    24 
    25                    if (count> 0) {
    26 
    27                       
    28 
    29                        try {
    30 
    31                             Thread.sleep(3000);
    32 
    33                             count--;
    34 
    35                        } catch (InterruptedException e) {
    36 
    37                             e.printStackTrace();
    38 
    39                        }
    40 
    41                       
    42 
    43                        System.out.println(Thread.currentThread().getName()+"卖出一张票,还剩" + count + "张票");
    44 
    45                    }
    46 
    47               }
    48 
    49          }
    50 
    51      }
    52 
    53 }

    总结

    synchronized(obj){}中的obj称为同步监视器

    同步代码块中同步监视器可以是任何对象,但是推荐使用共享资源作为同步监视器

    3)   同步方法

    如果同步代码(原子性)很多,可以考虑使用同步方法。

    把普通方法用synchronized修饰,同步方法的同步监视器是this(默认是this)

     1 public class MyRun implements Runnable {
     2 
     3    
     4 
     5     // 共享资源
     6 
     7     privateintcount = 5;
     8 
     9  
    10 
    11     @Override
    12 
    13     publicvoid run() {
    14 
    15         // 模拟一个窗口5个人
    16 
    17         for (inti = 0; i< 5; i++) {
    18 
    19            
    20 
    21             this.saleTicket();
    22 
    23            
    24 
    25         }
    26 
    27     }
    28 
    29    
    30 
    31     // 同步方法默认对this加锁
    32 
    33     private synchronized void saleTicket() {
    34 
    35         if (count> 0) {
    36 
    37            
    38 
    39             try {
    40 
    41                 Thread.sleep(3000);
    42 
    43                 count--;
    44 
    45             } catch (InterruptedException e) {
    46 
    47                 e.printStackTrace();
    48 
    49             }
    50 
    51            
    52 
    53             System.out.println(Thread.currentThread().getName()+"卖出一张票,还剩" + count + "张票");
    54 
    55         }
    56 
    57     }
    58 
    59 }

    8. 死锁

    线程t1,拥有A资源,再次申请B资源,线程t2,拥有B资源,再申请A资源,t1因为没有申请到B资源而进入阻塞;t2因为没有申请到A资源进入阻塞。此时两个线程都处于阻塞状态而不能正常结束,而此时cpu空转,这种情况称为死锁。

    9. 线程间通信

    线程的等待与唤醒称为线程之间的通信,等待与唤醒机制是实现两个或多个线程在执行任务过程相互配合相互协作的一种技术。

     object.wait   使当前线程等待(共享资源等待),无资源,让CPU,当前线程进入阻塞状态

    object.notify()  唤醒因为共享资源等待的线程,让其从阻塞状态进入就绪状态

    object------->指共享资源的对象 如需求的goodsStore

    优点:使用线程通信技术我们就可以让线程之间存在一定的关系,而不是每一个线程读是独立运行的,与其他线程无关

      使用wait,notify,notifyAll方法注意事项:

                                这些方法必须是锁对象(共享资源对象)调用

                                必须在同步代码块,或者是同步方法和cock和unlcok方法中间调用。

    需求:生产者生产一件商品消费者就消费一件商品,使其交替输出

     1  2 
     3 public class GoodsStore {
     4     private String brand;
     5     private String name;
     6     private boolean hasGoods = false;
     7 
     8     public String getBrand() {
     9         return brand;
    10     }
    11 
    12     public void setBrand(String brand) {
    13         this.brand = brand;
    14     }
    15 
    16     public String getName() {
    17         return name;
    18     }
    19 
    20     public void setName(String name) {
    21         this.name = name;
    22     }
    23 
    24     public boolean isHasGoods() {
    25         return hasGoods;
    26     }
    27 
    28     public void setHasGoods(boolean hasGoods) {
    29         this.hasGoods = hasGoods;
    30     }
    31 
    32     public GoodsStore() {
    33         super();
    34     }
    35 
    36     public GoodsStore(String brand, String name) {
    37         super();
    38         this.brand = brand;
    39         this.name = name;
    40     }
    41 
    42 }
     1  2 
     3 public class MyRun implements Runnable{
     4 
     5     private GoodsStore goodsStore=new GoodsStore();//共享资源
     6     
     7     public void run() {
     8         
     9         for(int i=0;i<6;i++){
    10             if(Thread.currentThread().getName().equals("生产者")){
    11                 synchronized(goodsStore){   //同步代码块
    12                     
    13                     if(goodsStore.isHasGoods()){  //如果goodsStore 里有商品执行这个if()代码块
    14                         try {
    15                             goodsStore.wait();    //使生产者线程等待(共享资源等待),没有资源,让出cpu ,由此生产者线程进入堵塞状态    
    16                         } catch (InterruptedException e) {
    17                             e.printStackTrace();
    18                         }
    19                     }
    20                     
    21                     if(i%2==0){  //当i为偶数时,生产者生产哇哈哈矿泉水
    22                         goodsStore.setBrand("哇哈哈");
    23                         goodsStore.setName("矿泉水");
    24                         
    25                         try {
    26                             Thread.sleep(1000);
    27                         } catch (InterruptedException e) {
    28                             e.printStackTrace();
    29                         }
    30                         System.out.println("生产者生产---"+goodsStore.getBrand()+goodsStore.getName());
    31                     }else{                //当i为奇数时,生产者生产旺仔小馒头
    32                         goodsStore.setBrand("旺仔");
    33                         goodsStore.setName("小馒头");
    34                         try {
    35                             Thread.sleep(1000);
    36                         } catch (InterruptedException e) {
    37                             e.printStackTrace();
    38                         }
    39                         System.out.println("生产者生产---"+goodsStore.getBrand()+goodsStore.getName());
    40                     }
    41                     goodsStore.setHasGoods(true);   //生产者生产了商品,变为有库存
    42                     goodsStore.notify();    //唤醒消费者线程消费(即唤醒等待的线程从阻塞状态变为就绪状态)
    43                 }
    44             }else{
    45                     synchronized(goodsStore){
    46                         
    47                         if(!goodsStore.isHasGoods()){   //如果goodsStore 没里有商品执行这个if()代码块
    48                             try {
    49                                 goodsStore.wait();    //使消费者线程等待(共享资源等待),没有资源,让出cpu ,由此消费者线程进入堵塞状态
    50                             } catch (InterruptedException e) {
    51                                 e.printStackTrace();
    52                             }
    53                         }
    54                         try {
    55                             Thread.sleep(1000);
    56                         } catch (InterruptedException e) {
    57                             e.printStackTrace();
    58                         }
    59                         System.out.println("消费者生产---"+goodsStore.getBrand()+goodsStore.getName());
    60                         
    61                         goodsStore.setHasGoods(false);   //消费者消费了商品,变为没有有库存
    62                         goodsStore.notify();        //唤醒生产者线程生产(即唤醒等待的线程从阻塞状态变为就绪状态)
    63                         
    64                     }
    65             }
    66         }
    67         
    68     }
    69     
    70 }
     1 public class Test01 {
     2     public static void main(String[]args){
     3         
     4         
     5         MyRun myRun=new MyRun();
     6         Thread t1=new Thread(myRun,"生产者");
     7         
     8         Thread t2=new Thread(myRun,"消费者");
     9         
    10         t1.start();
    11         t2.start();
    12         
    13         
    14     }
    15 }
  • 相关阅读:
    mysql/oracle 小技巧自动插入当前时间
    Java StringUtil 用法示例
    timestamp与String的相互转换
    gzip/gunzip用法
    maven常用指令
    微基站、宏基站区别
    CRAN方案
    让gvim中支持utf8编辑
    java正则表达式的几个小例子
    Sql Server数据库汉字按字母、笔划、拼音首字母、排序
  • 原文地址:https://www.cnblogs.com/qq2267711589/p/10828286.html
Copyright © 2020-2023  润新知