[JavaSE]第七章 多线程

[JavaSE]第七章 多线程,第1张

[JavaSE]第七章 多线程 7.1 基本概念
  • 程序的概念:是为完成特定任务、用某种语言编写的一组指令的集合。即指一段静态的代码,静态对象

  • 进程的概念:程序的一次执行过程,或是正在运行的一个程序。是一个动态的过程:有它自身的产生、存在和消亡的过程。——生命周期

  • 线程的概念:进程可进一步细化为线程,是一个程序内部的一条执行路径。

    • 若一个进程同一时间并行执行多个线程,就是支持多线程的
    • 线程作为调度和执行的单位,每个线程拥有独立的运行栈和程序计数器,线程切换的开销小
    • 一个进程中的多个线程共享相同的内存单元/内存地址空间它们从同一堆中分配对象,可以访问相同的变量和对象。这就使得线程间通信更简便、高效。但多个线程 *** 作共享的系统资源可能就会带来安全的隐患
  • 并行:多个CPU 同时执行多个任务。比如:多个人同时做不同的事。

  • 并发:一个CPU (采用时间片)同时执行多个任务。比如:秒杀、多个人做同一件事。

  • 多线程的优点:

    • 提高应用程序的响应。对图形化界面更有意义,可增强用户体验
    • 提高计算机系统 CPU 的利用率
    • 改善程序结构。将既长又复杂的进程分为多个线程,独立运行,利于理解和修改
  • 什么时候需要多线程:

    • 程序需要同时执行两个或多个任务
    • 程序需要实现一些需要等待的任务时,如用户输入、文件读写 *** 作、网络 *** 作、搜索等
    • 需要一些后台运行的程序时
7.2 线程的创建和使用 7.2.1 继承 Thread 类创建多线程
  • 创建步骤:
    • 1.创建一个继承于 Thread 类的子类
    • 2.重写 Thread 类的 run() --> 此线程执行的 *** 作声明在 run() 方法
    • 3.创建 Thread 类的子类的对象
    • 4.通过此对象调用 start()
//1.创建一个继承于 Thread 类的子类
class MyThread extends Thread {
    //2.重写 Thread 类的 run()
    @Override
    public void run() {

        for (int i = 0; i < 1000; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}
public class ThreadTest {

    public static void main(String[] args) {
        //3.创建 Thread 类的子类的对象
        MyThread t1 = new MyThread();

        //4.通过此对象调用 start():① 启动当前线程;② 调用当前线程的 run()
        t1.start();
        //问题一:我们不能通过直接调用 run() 的方式来启动线程
        //t1.run();

        //问题二:不能让已经 start() 的线程再去执行。会报 IllegalThreadStateException
        //t1.start();
        //我们需要重新创建一个线程的对象
        MyThread t2 = new MyThread();
        t2.start();

        for (int i = 0; i < 1000; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i + "********main()*********");
            }
        }

    }
}
7.2.2 实现 Runnable 接口创建多线程
  • 创建步骤:
    • 1.创建一个实现了 Runnable 接口的类
    • 2.实现类去实现 Runnable 中的抽象方法:run()
    • 3.创建实现类的对象
    • 4.将此对象作为参数传递到 Thread 类的构造器中,创建 Thread 类的对象
    • 5.通过 Thread 类的对象调用 start()
//1.创建一个实现了 Runnable 接口的类
class MyThread3 implements Runnable {

    //2.实现类去实现 Runnable 中的抽象方法:run()
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}

public class ThreadTest1 {

    public static void main(String[] args) {
        //3.创建实现类的对象
        MyThread3 t1 = new MyThread3();

        //4.将此对象作为参数传递到 Thread 类的构造器中,创建 Thread 类的对象
        Thread tt1 = new Thread(t1);

        //5.通过 Thread 类的对象调用 start()
        tt1.setName("tt1");
        tt1.start();

        //再启动一个线程,遍历 100 以内的偶数
        Thread tt2 = new Thread(t1);
        tt2.setName("tt2");
        tt2.start();
    }
}
7.2.3 两种实现多线程方式对比
  • 比较创建线程的两种方式
    • 开发中:优先选择实现 Runnable 接口的方式
    • 原因:
      • 1.实现的方式没有类的单继承的局限性
      • 2.实现的方式更适合来处理多个线程有共享数据的情况
  • 联系:public class Thread implements Runnable Thread 类 实现了 Runnable 接口
  • 相同点:两种方式都需要重写 run(),将线程要执行的逻辑声明在 run() 中
7.2.4 Thread 类的有关方法
  • void start():启动线程,并执行对象的 run()方法
  • run():线程在被调度时执行的 *** 作
  • String getName():返回线程的名称
  • void setName(String name):设置该线程名称
  • static Thread currentThread():返回当前线程
  • static void yield():线程让步
  • join():当某个程序执行中调用其他线程的 join()方法时,调用线程将被阻塞,直到join()加入的 join 线程执行完
  • static void sleep(long millis)
    • 令当前线程在指定时间段内放弃对 CPU 控制,使其他线程有机会被执行,时间到后重排队
    • 抛出 InterruptedException 异常
  • stop():强制结束线程生命周期,不推荐使用
  • boolean isAlive():判断线程是否存活
public class ThreadMethodTest {

    public static void main(String[] args) {

        //MyThread2 t1 = new MyThread2();
        //给线程命名(方式一)
        //t1.setName("线程一");

        //方式二
        MyThread2 t1 = new MyThread2("分线程一");
        t1.setPriority(Thread.MAX_PRIORITY);
        t1.start();
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
        //给主线程命名
        Thread.currentThread().setName("主线程");
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() + ":" + i + "********main()*********");
            }

            if (i == 20) {
                try {
                    t1.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        System.out.println(t1.isAlive());
    }
}

class MyThread2 extends Thread {

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {

//                try {
//                    sleep(10);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                System.out.println(getName() + ":" + getPriority() + ":" + i);
            }
            if (i % 20 == 0) {
                yield();
            }
        }
    }
    public MyThread2(String name) {
        super(name);
    }

    public MyThread2() {
    }
}
7.2.5 线程的调度
  • 调度策略
    • 时间片
    • 抢占式:高优先级的线程抢占 CPU
  • Java 的调度方法
    • 同优先级线程组成先进先出队列(先到先服务),使用时间片策略
    • 对高优先级,使用优先调度的抢占式策略
7.2.6 线程的优先级
  • 线程的优先级等级
    • MAX_PRIORITY:10
    • MIN _PRIORITY:1
    • NORM_PRIORITY:5
  • 涉及的方法
    • getPriority():返回线程优先值
    • setPriority(int newPriority):改变线程的优先级
  • 说明
    • 线程创建时继承父线程的优先级
    • 低优先级只是获得调度的概率低,并非一定是在高优先级线程之后才被调用
7.2.7 线程的分类

Java 中的线程分为两类:一种是守护线程,一种是用户线程

  • 它们在几乎每个方面都是相同的,唯一的区别是判断 JVM 何时离开
  • 守护线程是用来服务用户线程的,通过在 start()方法前调用 **thread.setDaemon(true) **可以把一个用户线程变成一个守护线程
  • Java 垃圾回收就是一个典型的守护线程
  • 若 JVM 中都是守护线程,当前 JVM 将退出
7.3 线程的生命周期
  • JDK 中用 Thread.State 类定义了线程的几种状态

  • 一个完整的生命周期中通常要经历如下的五种状态:

    • 新建:当一个 Thread 类或其子类的对象被声明并创建时,新生的线程对象处于新建状态
    • 就绪:处于新建状态的线程被 start() 后,将进入线程队列等待 CPU 时间片,此时它已具备了运行的条件,只是没分配到 CPU 资源
    • 运行:当就绪的线程被调度并获得 CPU 资源时,便进入运行状态, run() 方法定义了线程的 *** 作和功能
    • 阻塞:在某种特殊情况下,被人为挂起或执行输入输出 *** 作时,让出 CPU 并临时中止自己的执行,进入阻塞状态
    • 死亡:线程完成了它的全部工作或线程被提前强制性地中止或出现异常导致结束

7.4 线程的同步 7.4.1 线程安全问题
  • 多个线程执行的不确定性引起执行结果的不稳定
  • 多个线程对账本的共享,会造成 *** 作的不完整性,会破坏数据。
  • 以下列代码为例,在卖票的过程中可能会出现错票和重票的问题
class Window extends Thread {
    private static int ticket = 100;

    @Override
    public void run() {
        while (true) {
            if (ticket > 0) {
                try {
                    sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(getName() + ": 卖票,票号为:" + ticket);
                ticket --;
            } else {
                break;
            }
        }
    }
}

public class WindowTest {

    public static void main(String[] args) {

        Window t1 = new Window();
        Window t2 = new Window();
        Window t3 = new Window();

        t1.setName("窗口一");
        t2.setName("窗口二");
        t3.setName("窗口三");

        t1.start();
        t2.start();
        t3.start();
    }
}
7.4.2 同步代码块
  • 在 Java 中,我们通过同步机制,来解决线程的安全问题

  • synchronized(同步监视器) {
    	//需要被同步的代码
    }
    //1. *** 作共享数据的代码,即为需要被同步的代码。
    //2.共享数据:多个线程共同 *** 作的变量
    //3.同步监视器:俗称:锁。任何一个类的对象,都可以充当锁。要求:多个线程必须要共用同一把锁
    
    
  • 在实现 Runnable 接口创建多线程的方式中,我们可以考虑使用 this 充当同步监视器

  • 同步的方式,解决了线程的安全问题。

  • *** 作同步代码时,只能有一个线程参与,其他线程等待。相当于是一个单线程的过程,效率低。

  • 使用同步代码块解决继承 Thread 类的方式的线程安全问题

    • 在继承 Thread 类创建多线程的方式中,慎用 this 充当同步监视器,考虑使用当前类充当同步监视器
    class Window extends Thread {
        private static int ticket = 100;
        private static final Object obj = new Object();
        @Override
        public void run() {
            while (true) {
                //synchronized (this) { //错误的,this 代表 t1,t2,t3
                //synchronized (obj) { //正确的
                synchronized (Window.class) { // Class clazz = Window.class;
                    if (ticket > 0) {
                        System.out.println(getName() + ": 卖票,票号为:" + ticket);
                        ticket --;
                    } else {
                        break;
                    }
                }
            }
        }
    }
    
    public class WindowTest {
    
        public static void main(String[] args) {
    
            Window t1 = new Window();
            Window t2 = new Window();
            Window t3 = new Window();
    
            t1.setName("窗口一");
            t2.setName("窗口二");
            t3.setName("窗口三");
    
            t1.start();
            t2.start();
            t3.start();
        }
    }
    
  • 使用同步代码块解决实现 Runnable 接口的方式的线程安全问题

    class Window1 implements Runnable {
        private int ticket = 100;
        final Object obj = new Object();
    
        @Override
        public void run() {
            while (true) {
                synchronized(this) { //此时的 this:唯一的 Window1 的对象
                    if (ticket > 0) {
                        System.out.println(Thread.currentThread().getName() + ":" + ticket);
                        ticket --;
                    } else {
                        break;
                    }
                }
            }
        }
    }
    
    
    public class WindowTest1 {
    
        public static void main(String[] args) {
    
            Window1 w1 = new Window1();
    
            Thread t1 = new Thread(w1);
            t1.setName("窗口1");
            Thread t2 = new Thread(w1);
            t2.setName("窗口2");
            Thread t3 = new Thread(w1);
            t3.setName("窗口3");
    
            t1.start();
            t2.start();
            t3.start();
        }
    }
    
7.4.3 同步方法
  • 如果 *** 作共享数据的代码完整的声明在一个方法中,我们不妨将此方法声明为同步的

  • 同步方法仍然涉及到同步监视器,只是不需要我们显式的声明。

  • 非静态的同步方法,同步监视器:this

  • 静态的同步方法,同步监视器:当前类本身

  • 使用同步方法来处理继承 Thread 类的线程安全问题

    class Window2 extends Thread {
        private static int ticket = 100;
    
        @Override
        public void run() {
            while (ticket > 0) {
                show();
            }
        }
    
        //private synchronized void show() { //错误的,t1,t2,t3
        private static synchronized void show() {
            if (ticket > 0) {
                System.out.println(Thread.currentThread().getName() + ": 卖票,票号为:" + ticket);
                ticket --;
            }
        }
    }
    
    
    public class WindowTest2 {
        public static void main(String[] args) {
    
            Window2 t1 = new Window2();
            Window2 t2 = new Window2();
            Window2 t3 = new Window2();
    
            t1.setName("窗口一");
            t2.setName("窗口二");
            t3.setName("窗口三");
    
            t1.start();
            t2.start();
            t3.start();
        }
    }
    
  • 使用同步方法解决实现 Runnable 接口的方式的线程安全问题

    class Window3 implements Runnable {
    
        private int ticket = 100;
    
        @Override
        public void run() {
            while (ticket > 0) {
                show();
            }
        }
    
        private synchronized void show() {
            if (ticket > 0) {
                System.out.println(Thread.currentThread().getName() + ":" + ticket);
                ticket--;
            }
        }
    }
    
    public class WindowTest3 {
        public static void main(String[] args) {
    
            Window3 w1 = new Window3();
    
            Thread t1 = new Thread(w1);
            t1.setName("窗口1");
            Thread t2 = new Thread(w1);
            t2.setName("窗口2");
            Thread t3 = new Thread(w1);
            t3.setName("窗口3");
    
            t1.start();
            t2.start();
            t3.start();
        }
    }
    
7.4.4 Lock 锁
  • 解决线程安全问题的方式三:Lock 锁 – JDK5.0新增

  • synchronized 与 Lock 的异同?

    • 相同:二者都可以解决线程安全问题
    • 不同:
      • synchronized 机制在执行完相应的同步代码以后,自动的释放同步监视器
      • Lock 需要手动的启动同步(lock()),同时结束同步也需要手动的实现(unlock())
  • 优先使用顺序:Lock -> 同步代码块(已经进行了方法体,分配了相关资源) -> 同步方法(在方法体之外)

    class Window implements Runnable {
      private int ticket = 100;
    
      //1.实例化 ReentrantLock
      private ReentrantLock lock = new ReentrantLock();
    
      @Override
      public void run() {
          while (true) {
              try {
                  //2.调用锁定方法 lock()
                  lock.lock();
                  if (ticket > 0) {
                      try {
                          Thread.sleep(50);
                      } catch (InterruptedException e) {
                          e.printStackTrace();
                      }
    
                      System.out.println(Thread.currentThread().getName() + ": 卖票,票号为:" + ticket);
                      ticket --;
                  } else {
                      break;
                  }
              } finally {
                  //3.调用解锁方法 unlock()
                  lock.unlock();
              }
          }
      }
    }
    
    public class LockTest {
    
        public static void main(String[] args) {
        
            Window w = new Window();
        
            Thread t1 = new Thread(w);
            Thread t2 = new Thread(w);
            Thread t3 = new Thread(w);
        
            t1.setName("窗口一");
            t2.setName("窗口二");
            t3.setName("窗口三");
        
            t1.start();
            t2.start();
            t3.start();
        }
    }
    
7.4.5 死锁问题
  • 死锁的理解:不同的线程分别占用对方需要的同步资源不放弃,都在等待对方放弃自己需要的同步资源,进行成了线程的死锁
  • 出现死锁后,不会出现异常,不会出现提示,只是所有的线程都处于阻塞状态,无法继续
public class ThreadTest {
    public static void main(String[] args) {

        StringBuffer s1 = new StringBuffer();
        StringBuffer s2 = new StringBuffer();

        new Thread(){
            @Override
            public void run() {
                synchronized (s1) {
                    s1.append("a");
                    s2.append("1");

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    synchronized (s2) {
                        s1.append("b");
                        s2.append("2");

                        System.out.println(s1);
                        System.out.println(s2);
                    }
                }
            }
        }.start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (s2) {
                    s1.append("c");
                    s2.append("3");

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    synchronized (s1) {
                        s1.append("d");
                        s2.append("4");

                        System.out.println(s1);
                        System.out.println(s2);
                    }
                }
            }
        }).start();
    }
}
7.5 线程的通信
  • wait():一旦执行此方法,当前线程就进入阻塞状态,并释放同步监视器
  • notify():一旦执行此方法,就会唤醒被 wait 的一个线程。如果有多个线程被 wait,就唤醒优先级高的那个
  • notifyAll():一旦执行此方法,就会唤醒所有被 wait 的线程
  • wait(),notify(),notifyAll() 三个方法必须使用在同步方法块或同步方法当中
  • wait(),notify(),notifyAll() 三个方法的调用者必须是同步代码块或同步方法中的同步监视器。否则,会出现 IllegalMonitorStateException 异常
  • wait(),notify(),notifyAll() 三个方法是定义在 java.lang.Object 类中
  • sleep() 和 wait() 的异同?
    • 相同点:一旦执行方法,都可以使得当前的线程进入阻塞状态
    • 不同点:
      • 两个方法声明的位置不同:Thread 类中声明 sleep(),Object 类中声明 wait()
      • 调用的要求不同:sleep() 可以在任何需要的场景下调用。wait() 必须使用在同步代码块或同步方法中调用
      • 关于是否释放同步监视器:如果两个方法都使用在同步代码块或同步方法中,sleep() 不会释放锁,wait() 会释放锁
class Number implements Runnable {

    private int number = 1;

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                notify();
                if (number < 100) {

                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + ":" + number);
                    number ++;

                    try {
                        wait();//调用wait()方法的线程进入堵塞状态
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }
            }
        }
    }
}

public class communicationTest {

    public static void main(String[] args) {

        Number number = new Number();

        Thread t1 = new Thread(number);
        Thread t2 = new Thread(number);

        t1.setName("线程1");
        t2.setName("线程2");

        t1.start();
        t2.start();
    }

}
7.6 JDK5.0 新增线程创建方式 7.6.1 实现 Callable 接口创建多线程
  • 如何理解实现 Callable 接口的方式创建多线程的方式比 实现 Runnable 接口创建多线程的方式强大?

    • call()可以有返回值

    • call()可以抛出异常,被外面的 *** 作捕获,获取异常的信息

    • Callable 可以支持泛型

//1.创建一个 Callable 的实现类
class NumThread implements Callable {

    //2.实现 call 方法,将此线程需要执行的 *** 作声明在 call() 中
    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            if (i % 2 == 0) {
                System.out.println(i);
                sum += i;
            }
        }
        return sum;
    }
}
public class ThreadNew {

    public static void main(String[] args) {
        //3.创建Callable接口实现类的对象
        NumThread numThread = new NumThread();

        //4.将此Callable接口实现类的对象FutureTask构造器中,创建FutureTask的对象
        FutureTask task = new FutureTask(numThread);

        //5.将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread类的对象,并调用start()
        Thread t1 = new Thread(task);
        t1.start();

        try {
            //6.get() 返回值即为FutureTask构造器参数Callable实现类重写的call()的返回值
            Object sum = task.get();
            System.out.println("总和为:" + sum);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
7.6.2 使用线程池
  • 好处:
    • 1.提高响应速度(减少了创建新线程的时间)
    • 2.降低资源消耗(重复利用线程池中线程,不需要每次都创建)
    • 3.便于线程管理
      • corePoolSize:核心池的大小
      • maximumPoolSize:最大线程数
      • keepAliveTime:线程没有任务时最多保持多长时间后会终止
class NumberThread implements Runnable {

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}

class NumberThread2 implements Runnable {

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            if (i % 2 != 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}

class NumberThread3 implements Callable {

    @Override
    public Integer call() throws Exception {
        for (int i = 1; i <= 100; i++) {
            if (i % 10 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
        return null;
    }
}

public class ThreadPool {

    public static void main(String[] args) {

        //1.提供指定线程数量的线程池
        ExecutorService service = Executors.newFixedThreadPool(10);
        ThreadPoolExecutor service2 = (ThreadPoolExecutor) service;
//        service2.setCorePoolSize(15);


        System.out.println(service.getClass());
        //2.执行指定的线程的操作。需要提供实现Runnable接口或Callable接口的实现类的对象
        service.execute(new NumberThread());//适合用于Runnable
        service.execute(new NumberThread2());

        service.submit(new NumberThread3());//适合用于Callable

        //3.关闭连接池
        service.shutdown();
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5686219.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存