Java多线程和线程同步

Java多线程和线程同步

进程和线程

  • 进程和线程

    • 操作系统中运行多个软件
    • 一个运行中的软件可能包含多个进程
    • 一个运行中的进程可能包含多个线程
  • CPU线程和操作系统线程

    • CPU线程
      • 多核CPU的每个核各自独立运行,因此每个核一个线程
      • “四核八线程”:CPU硬件方在硬件级别对CPU进行了一核多线程的支持(本质上依然是每个核一个线程)
      • 单核CPU也可以运行多线程操作系统
  • 线程是什么:按代码顺序执行下来,执行完毕就结束的一条线

    • UI线程为什么不会结束?

      因为它在初始化完毕后会执行死循环,循环的内容是刷新界面

多线程的使用

  • Thread 和 Runnable

    • Thread

      1
      2
      3
      4
      5
      6
      7
      Thread thread = new Thread(){
      @Override
      public void run(){
      System.out.println("Thread started!");
      }
      };
      thread.start();
    • Runnable

      1
      2
      3
      4
      5
      6
      7
      8
      Runnable runnable = new Runnable(){
      @Override
      public void run(){
      System.out.println("Thread with Runnable started!");
      }
      };
      Thread thread = new Thread(runnable);
      thread.start();
    • ThreadFactory

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      ThreadFactory factory = new ThreadFactory(){
      int count = 0;
      @Override
      public Thread newThread(Runnable r){
      count++;
      return new Thread(r, "Thread - " + count);
      }
      };
      Runnable runnable = new Runnable(){
      @Override
      public void run(){
      System.out.println("Thread.currentThread().getName() " + " started!");
      }
      }
      Thread thread = factory.newThread(runnable);
      thread.start();
      Thread thread1 = factory.newThread(runnable);
      thread1.start();
    • Executor 和线程池

      • 常用:newCachedThreadPool()

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        Runnable runnable = new Runnable(){
        @Override
        public void run(){
        System.out.println("Thread with Runnable started!");
        }
        };
        Executor executor = Executors.newCachedThreadPool();
        executor.execute(runnable);
        executor.execute(runnable);
        executor.execute(runnable);
      • 短时批量处理:newFixedThreadPool()

        1
        2
        3
        4
        5
        ExecutorService executor = Executors.newFixedThreadPool(20);
        for(Bitmap bitmap: bitmaps){
        executor.execute(bitmapProcessor(bitmap));
        }
        executor.shutdown();
    • Callable 和 Future

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      Callable<String> callable = new Callable<String>(){
      @Override
      public String call(){
      try{
      Thread.sleep(1500);
      } catch (InterruptedException e){
      e.printStackTrace();
      }
      return "Done!";
      }
      };
      ExecutorService executor = Executors.newCachedThreadPool();
      Future<String> future = executor.submit(callable);
      try{
      String result = future.get();
      System.out.println("result: " + result);
      } catch (InterruptedException | ExecutionException e){
      e.printStackTrace();
      }

线程同步和线程安全

  • synchronized

    • synchronized 方法

      1
      2
      3
      4
      5
      6
      7
      private synchronized void count(int newValue){
      x = newValue;
      y = newValue;
      if(x != y){
      System.out.println("x: " + x + " , y: "+ y);
      }
      }
    • synchronized 代码块

      1
      2
      3
      4
      5
      6
      7
      8
      9
      private void count(int newValue){
      synchronized(this){
      x = newValue;
      y = newValue;
      if(x != y){
      System.out.println("x: " + x + " , y: "+ y);
      }
      }
      }
      1
      2
      3
      4
      5
      synchronized(monitor1){
      synchronized(monitor2){
      name = x + "-" + y;
      }
      }
    • synchronized 的本质

      • 保证方法内部或代码块内部资源(数据)的互斥访问。即同一时间、由同一个Monitor监视的代码,最多只能有一个线程在访问

        image-20221219100714539

      • 保证线程之间对监视资源的数据同步。即,任何线程在获取到Monitor后的第一时间,会先将共享内存中的数据复制到自己的缓存中;任何线程在释放Monitor的第一时间,会先将缓存中的数据复制到共享内存中。

        image-20221219100942682

  • volatile

    • 保证加了volatile关键字的字段的操作具有原子性同步性,其中原子性相当于实现了针对单一字段的线程间互斥访问。因此volatile可以看作简化版的synchronized
    • volatile只对基本类型(byte、char、short、int、long、float、double、boolean)的赋值操作和对象的引用赋值操作有效。
  • java.util.concurrent.atomic包:

    • 下面有AtomicInteger AtomicBoolean等类,作用和volatile基本一致,可以看作是通用版的volatile

      1
      2
      3
      AtomicInteger atomicInteger = new AtomicInteger(0);
      //...
      atomicInteger.getAndIncrement();
  • Lock / ReentrantReadWriteLock

    • 同样是“加锁”机制。但使用方式更灵活,同时也更麻烦一些。

      1
      2
      3
      4
      5
      6
      7
      8
      Lock lock = new ReentrantLock();
      //...
      lock.lock();
      try{
      x ++;
      } finally{
      lock.unlock();
      }

      finally的作用:保证在方法提前结束或出现 Exception 的时候,依然能正常释放锁。

    • 一般并不会只是使用Lock,而是会使用更复杂的锁,例如ReadWriteLock

      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
      ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
      Lock readLock = lock.readLock();
      Lock writeLock = lock.writeLock();

      private int x = 0;
      private void count(){
      writeLock.lock();
      try{
      x++;
      } finally{
      writeLock.unlock();
      }
      }

      private void print(int time){
      readLock.lock();
      try {
      for(int i = 0; i < tiem; i++){
      System.out.print(x + " ");
      }
      System.out.println();
      } finally {
      readLock.unlock();
      }
      }
  • 线程安全问题的本质:

    在多个线程访问共同的资源时,在某一个线程对资源进行写操作的中途(写入已经开始,但还没结束),其他线程对这个写了一半的资源进行了读操作。或者基于这个写了一半的资源进行了写操作,导致出现数据错误

  • 锁机制的本质:

    通过对共享资源进行访问限制,让同一时间只有一个线程可以访问资源,保证了数据的准确性。

  • 不论是线程安全问题,还是针对线程安全问题所衍生出的锁机制,它们的核心都在于共享的资源,而不是某个方法或者某几行代码。