• Java回顾之多线程


    在这篇文章里,我们关注多线程。多线程是一个复杂的话题,包含了很多内容,这篇文章主要关注线程的基本属性、如何创建线程、线程的状态切换以及线程通信,我们把线程同步的话题留到下一篇文章中。

      线程是操作系统运行的基本单位,它被封装在进程中,一个进程可以包含多个线程。即使我们不手动创造线程,进程也会有一个默认的线程在运行。

      对于JVM来说,当我们编写一个单线程的程序去运行时,JVM中也是有至少两个线程在运行,一个是我们创建的程序,一个是垃圾回收。

      线程基本信息

      我们可以通过Thread.currentThread()方法获取当前线程的一些信息,并对其进行修改。

      我们来看以下代码:

     
     1 String name = Thread.currentThread().getName();
     2         int priority = Thread.currentThread().getPriority();
     3         String groupName = Thread.currentThread().getThreadGroup().getName();
     4         boolean isDaemon = Thread.currentThread().isDaemon();
     5         System.out.println("Thread Name:" + name);
     6         System.out.println("Priority:" + priority);
     7         System.out.println("Group Name:" + groupName);
     8         System.out.println("IsDaemon:" + isDaemon);
     9         
    10         Thread.currentThread().setName("Test");
    11         Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    12         name = Thread.currentThread().getName();
    13         priority = Thread.currentThread().getPriority();
    14         groupName = Thread.currentThread().getThreadGroup().getName();
    15         isDaemon = Thread.currentThread().isDaemon();
    16         System.out.println("Thread Name:" + name);
    17         System.out.println("Priority:" + priority);    
     

      其中列出的属性说明如下:

    • GroupName,每个线程都会默认在一个线程组里,我们也可以显式的创建线程组,一个线程组中也可以包含子线程组,这样线程和线程组,就构成了一个树状结构。
    • Name,每个线程都会有一个名字,如果不显式指定,那么名字的规则是“Thread-xxx”。
    • Priority,每个线程都会有自己的优先级,JVM对优先级的处理方式是“抢占式”的。当JVM发现优先 级高的线程时,马上运行该线程;对于多个优先级相等的线程,JVM对其进行轮询处理。Java的线程优先级从1到10,默认是5,Thread类定义了2 个常量:MIN_PRIORITY和MAX_PRIORITY来表示最高和最低优先级。
      我们可以看下面的代码,它定义了两个不同优先级的线程:
       
       1 public static void priorityTest()
       2 {
       3     Thread thread1 = new Thread("low")
       4     {
       5         public void run()
       6         {
       7             for (int i = 0; i < 5; i++)
       8             {
       9                 System.out.println("Thread 1 is running.");
      10             }
      11         }
      12     };
      13     
      14     Thread thread2 = new Thread("high")
      15     {
      16         public void run()
      17         {
      18             for (int i = 0; i < 5; i++)
      19             {
      20                 System.out.println("Thread 2 is running.");
      21             }
      22         }
      23     };
      24     
      25     thread1.setPriority(Thread.MIN_PRIORITY);
      26     thread2.setPriority(Thread.MAX_PRIORITY);
      27     thread1.start();
      28     thread2.start();
      29 }
       
      从运行结果可以看出,是高优先级线程运行完成后,低优先级线程才运行。
    • isDaemon,这个属性用来控制父子线程的关系,如果设置为true,当父线程结束后,其下所有子线程也结束,反之,子线程的生命周期不受父线程影响。
      我们来看下面的例子:
       
       1 public static void daemonTest()
       2 {
       3     Thread thread1 = new Thread("daemon")
       4     {
       5         public void run()
       6         {
       7             Thread subThread = new Thread("sub")
       8             {
       9                 public void run()
      10                 {
      11                     for(int i = 0; i < 100; i++)
      12                     {
      13                         System.out.println("Sub Thread Running " + i);
      14                     }
      15                 }
      16             };
      17             subThread.setDaemon(true);
      18             subThread.start();
      19             System.out.println("Main Thread end.");
      20         }
      21     };
      22     
      23     thread1.start();
      24 }
       

      上面代码的运行结果,在和删除subThread.setDaemon(true);后对比,可以发现后者运行过程中子线程会完成执行后再结束,而前者中,子线程很快就结束了。

      如何创建线程

      上面的内容,都是演示默认线程中的一些信息,那么应该如何创建线程呢?在Java中,我们有3种方式可以用来创建线程。

      Java中的线程要么继承Thread类,要么实现Runnable接口,我们一一道来。

      使用内部类来创建线程

      我们可以使用内部类的方式来创建线程,过程是声明一个Thread类型的变量,并重写run方法。示例代码如下:

     
     1 public static void createThreadByNestClass()
     2 {
     3     Thread thread = new Thread()
     4     {
     5         public void run()
     6         {
     7             for (int i =0; i < 5; i++)
     8             {
     9                 System.out.println("Thread " + Thread.currentThread().getName() + " is running.");
    10             }
    11             System.out.println("Thread " + Thread.currentThread().getName() + " is finished.");
    12         }
    13     };
    14     thread.start();
    15 }
     

      继承Thread以创建线程

      我们可以从Thread中派生一个类,重写其run方法,这种方式和上面相似。示例代码如下:

     
     1 class MyThread extends Thread
     2 {
     3     public void run()
     4     {
     5         for (int i =0; i < 5; i++)
     6         {
     7             System.out.println("Thread " + Thread.currentThread().getName() + " is running.");
     8         }
     9         System.out.println("Thread " + Thread.currentThread().getName() + " is finished.");
    10     }
    11 }
    12 
    13 
    14 public static void createThreadBySubClass()
    15 {
    16     MyThread thread = new MyThread();
    17     thread.start();
    18 }
     

      实现Runnable接口以创建线程

      我们可以定义一个类,使其实现Runnable接口,然后将该类的实例作为构建Thread变量构造函数的参数。示例代码如下:

     
     1 class MyRunnable implements Runnable
     2 {
     3     public void run() 
     4     {
     5         for (int i =0; i < 5; i++)
     6         {
     7             System.out.println("Thread " + Thread.currentThread().getName() + " is running.");
     8         }
     9         System.out.println("Thread " + Thread.currentThread().getName() + " is finished.");
    10     }
    11 }
    12 
    13 
    14 public static void createThreadByRunnable()
    15 {
    16     MyRunnable runnable = new MyRunnable();
    17     Thread thread = new Thread(runnable);
    18     thread.start();
    19 }
     

      上述3种方式都可以创建线程,而且从示例代码上看,线程执行的功能是一样的,那么这三种创建方式有什么不同呢?

      这涉及到Java中多线程的运行模式,对于Java来说,多线程在运行时,有“多对象多线程”和“单对象多线程”的区别:

    • 多对象多线程,程序在运行过程中创建多个线程对象,每个对象上运行一个线程。
    • 单对象多线程,程序在运行过程中创建一个线程对象,在其上运行多个线程。

      显然,从线程同步和调度的角度来看,多对象多线程要简单一些。上述3种线程创建方式,前两种都属于“多对象多线程”,第三种既可以使用“多对象多线程”,也可以使用“单对象单线程”。

      我们来看下面的示例代码,里面会用到Object.notify方法,这个方法会唤醒对象上的一个线程;而Object.notifyAll方法,则会唤醒对象上的所有线程。

     
      1 public class NotifySample {
      2     
      3     public static void main(String[] args) throws InterruptedException
      4     {
      5         notifyTest();
      6         notifyTest2();
      7         notifyTest3();
      8     }
      9     
     10     private static void notifyTest() throws InterruptedException
     11     {
     12         MyThread[] arrThreads = new MyThread[3];
     13         for (int i = 0; i < arrThreads.length; i++)
     14         {
     15             arrThreads[i] = new MyThread();
     16             arrThreads[i].id = i;
     17             arrThreads[i].setDaemon(true);
     18             arrThreads[i].start();
     19         }
     20         Thread.sleep(500);
     21         for (int i = 0; i < arrThreads.length; i++)
     22         {
     23             synchronized(arrThreads[i])
     24             {
     25                 arrThreads[i].notify();
     26             }
     27         }
     28     }
     29     
     30     private static void notifyTest2() throws InterruptedException
     31     {
     32         MyRunner[] arrMyRunners = new MyRunner[3];
     33         Thread[] arrThreads = new Thread[3];
     34         for (int i = 0; i < arrThreads.length; i++)
     35         {
     36             arrMyRunners[i] = new MyRunner();
     37             arrMyRunners[i].id = i;
     38             arrThreads[i] = new Thread(arrMyRunners[i]);
     39             arrThreads[i].setDaemon(true);
     40             arrThreads[i].start();
     41         }
     42         Thread.sleep(500);
     43         for (int i = 0; i < arrMyRunners.length; i++)
     44         {
     45             synchronized(arrMyRunners[i])
     46             {
     47                 arrMyRunners[i].notify();
     48             }
     49         }
     50     }
     51     
     52     private static void notifyTest3() throws InterruptedException
     53     {
     54         MyRunner runner = new MyRunner();
     55         Thread[] arrThreads = new Thread[3];
     56         for (int i = 0; i < arrThreads.length; i++)
     57         {
     58             arrThreads[i] = new Thread(runner);
     59             arrThreads[i].setDaemon(true);
     60             arrThreads[i].start();
     61         }
     62         Thread.sleep(500);
     63 
     64         synchronized(runner)
     65         {
     66             runner.notifyAll();
     67         }
     68     }
     69 }
     70 
     71 class MyThread extends Thread
     72 {
     73     public int id = 0;
     74     public void run()
     75     {
     76         System.out.println("第" + id + "个线程准备休眠5分钟。");
     77         try
     78         {
     79             synchronized(this)
     80             {
     81                 this.wait(5*60*1000);
     82             }
     83         }
     84         catch(InterruptedException ex)
     85         {
     86             ex.printStackTrace();
     87         }
     88         System.out.println("第" + id + "个线程被唤醒。");
     89     }
     90 }
     91 
     92 class MyRunner implements Runnable
     93 {
     94     public int id = 0;
     95     public void run() 
     96     {
     97         System.out.println("第" + id + "个线程准备休眠5分钟。");
     98         try
     99         {
    100             synchronized(this)
    101             {
    102                 this.wait(5*60*1000);
    103             }
    104         }
    105         catch(InterruptedException ex)
    106         {
    107             ex.printStackTrace();
    108         }
    109         System.out.println("第" + id + "个线程被唤醒。");
    110     }
    111     
    112 }
     

      示例代码中,notifyTest()和notifyTest2()是“多对象多线程”,尽管notifyTest2()中的线程实现了 Runnable接口,但是它里面定义Thread数组时,每个元素都使用了一个新的Runnable实例。notifyTest3()属于“单对象多线 程”,因为我们只定义了一个Runnable实例,所有的线程都会使用这个实例。

      notifyAll方法适用于“单对象多线程”的情景,因为notify方法只会随机唤醒对象上的一个线程。

      线程的状态切换

      对于线程来讲,从我们创建它一直到线程运行结束,在这个过程中,线程的状态可能是这样的:

    • 创建:已经有Thread实例了, 但是CPU还有为其分配资源和时间片。
    • 就绪:线程已经获得了运行所需的所有资源,只等CPU进行时间调度。
    • 运行:线程位于当前CPU时间片中,正在执行相关逻辑。
    • 休眠:一般是调用Thread.sleep后的状态,这时线程依然持有运行所需的各种资源,但是不会被CPU调度。
    • 挂起:一般是调用Thread.suspend后的状态,和休眠类似,CPU不会调度该线程,不同的是,这种状态下,线程会释放所有资源。
    • 死亡:线程运行结束或者调用了Thread.stop方法。

      下面我们来演示如何进行线程状态切换,首先我们会用到下面方法:

    • Thread()或者Thread(Runnable):构造线程。
    • Thread.start:启动线程。
    • Thread.sleep:将线程切换至休眠状态。
    • Thread.interrupt:中断线程的执行。
    • Thread.join:等待某线程结束。
    • Thread.yield:剥夺线程在CPU上的执行时间片,等待下一次调度。
    • Object.wait:将Object上所有线程锁定,直到notify方法才继续运行。
    • Object.notify:随机唤醒Object上的1个线程。
    • Object.notifyAll:唤醒Object上的所有线程。

      下面,就是演示时间啦!!!

      线程等待与唤醒

      这里主要使用Object.wait和Object.notify方法,请参见上面的notify实例。需要注意的是,wait和notify 都必须针对同一个对象,当我们使用实现Runnable接口的方式来创建线程时,应该是在Runnable对象而非Thread对象上使用这两个方法。

      线程的休眠与唤醒

     
     1 public class SleepSample {
     2     
     3     public static void main(String[] args) throws InterruptedException
     4     {
     5         sleepTest();
     6     }
     7     
     8     private static void sleepTest() throws InterruptedException
     9     {
    10         Thread thread = new Thread()
    11         {
    12             public void run()
    13             {
    14                 System.out.println("线程 " + Thread.currentThread().getName() + "将要休眠5分钟。");
    15                 try
    16                 {
    17                     Thread.sleep(5*60*1000);
    18                 }
    19                 catch(InterruptedException ex)
    20                 {
    21                     System.out.println("线程 " + Thread.currentThread().getName() + "休眠被中断。");
    22                 }
    23                 System.out.println("线程 " + Thread.currentThread().getName() + "休眠结束。");
    24             }
    25         };
    26         thread.setDaemon(true);
    27         thread.start();
    28         Thread.sleep(500);
    29         thread.interrupt();
    30     }
    31 
    32 }
     

      线程在休眠过程中,我们可以使用Thread.interrupt将其唤醒,这时线程会抛出InterruptedException。

      线程的终止

      虽然有Thread.stop方法,但该方法是不被推荐使用的,我们可以利用上面休眠与唤醒的机制,让线程在处理IterruptedException时,结束线程。

     
     1 public class StopThreadSample {
     2 
     3     public static void main(String[] args) throws InterruptedException
     4     {
     5         stopTest();
     6     }
     7     
     8     private static void stopTest() throws InterruptedException
     9     {
    10         Thread thread = new Thread()
    11         {
    12             public void run()
    13             {
    14                 System.out.println("线程运行中。");
    15                 try
    16                 {
    17                     Thread.sleep(1*60*1000);
    18                 }
    19                 catch(InterruptedException ex)
    20                 {
    21                     System.out.println("线程中断,结束线程");
    22                     return;
    23                 }
    24                 System.out.println("线程正常结束。");
    25             }
    26         };
    27         thread.start();
    28         Thread.sleep(500);
    29         thread.interrupt();
    30     }
    31 }
     

      线程的同步等待

      当我们在主线程中创建了10个子线程,然后我们期望10个子线程全部结束后,主线程在执行接下来的逻辑,这时,就该Thread.join登场了。

     
     1 public class JoinSample {
     2 
     3     public static void main(String[] args) throws InterruptedException
     4     {
     5         joinTest();
     6     }
     7     
     8     private static void joinTest() throws InterruptedException
     9     {
    10         Thread thread = new Thread()
    11         {
    12             public void run()
    13             {
    14                 try
    15                 {
    16                     for(int i = 0; i < 5; i++)
    17                     {
    18                         System.out.println("线程在运行。");
    19                         Thread.sleep(1000);
    20                     }
    21                 }
    22                 catch(InterruptedException ex)
    23                 {
    24                     ex.printStackTrace();
    25                 }
    26             }
    27         };
    28         thread.setDaemon(true);
    29         thread.start();
    30         Thread.sleep(1000);
    31         thread.join();
    32         System.out.println("主线程正常结束。");
    33     }
    34 }
     

      我们可以试着将thread.join();注释或者删除,再次运行程序,就可以发现不同了。

      线程间通信

      我们知道,一个进程下面的所有线程是共享内存空间的,那么我们如何在不同的线程之间传递消息呢?在回顾 Java I/O时,我们谈到了PipedStream和PipedReader,这里,就是它们发挥作用的地方了。

      下面的两个示例,功能完全一样,不同的是一个使用Stream,一个使用Reader/Writer。

     
     1 public static void communicationTest() throws IOException, InterruptedException
     2 {
     3     final PipedOutputStream pos = new PipedOutputStream();
     4     final PipedInputStream pis = new PipedInputStream(pos);
     5     
     6     Thread thread1 = new Thread()
     7     {
     8         public void run()
     9         {
    10             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    11             try
    12             {
    13                 while(true)
    14                 {
    15                     String message = br.readLine();
    16                     pos.write(message.getBytes());
    17                     if (message.equals("end")) break;
    18                 }
    19                 br.close();
    20                 pos.close();
    21             }
    22             catch(Exception ex)
    23             {
    24                 ex.printStackTrace();
    25             }
    26         }
    27     };
    28     
    29     Thread thread2 = new Thread()
    30     {
    31         public void run()
    32         {
    33             byte[] buffer = new byte[1024];
    34             int bytesRead = 0;
    35             try
    36             {
    37                 while((bytesRead = pis.read(buffer, 0, buffer.length)) != -1)
    38                 {
    39                     System.out.println(new String(buffer));
    40                     if (new String(buffer).equals("end")) break;
    41                     buffer = null;
    42                     buffer = new byte[1024];
    43                 }
    44                 pis.close();
    45                 buffer = null;
    46             }
    47             catch(Exception ex)
    48             {
    49                 ex.printStackTrace();
    50             }
    51         }
    52     };
    53     
    54     thread1.setDaemon(true);
    55     thread2.setDaemon(true);
    56     thread1.start();
    57     thread2.start();
    58     thread1.join();
    59     thread2.join();
    60 }
     

     1 private static void communicationTest2() throws InterruptedException, IOException
     2 {
     3     final PipedWriter pw = new PipedWriter();
     4     final PipedReader pr = new PipedReader(pw);
     5     final BufferedWriter bw = new BufferedWriter(pw);
     6     final BufferedReader br = new BufferedReader(pr);
     7     
     8     Thread thread1 = new Thread()
     9     {
    10         public void run()
    11         {
    12             
    13             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    14             try
    15             {
    16                 while(true)
    17                 {
    18                     String message = br.readLine();
    19                     bw.write(message);
    20                     bw.newLine();
    21                     bw.flush();
    22                     if (message.equals("end")) break;
    23                 }
    24                 br.close();
    25                 pw.close();
    26                 bw.close();
    27             }
    28             catch(Exception ex)
    29             {
    30                 ex.printStackTrace();
    31             }
    32         }
    33     };
    34     
    35     Thread thread2 = new Thread()
    36     {
    37         public void run()
    38         {
    39             
    40             String line = null;
    41             try
    42             {
    43                 while((line = br.readLine()) != null)
    44                 {
    45                     System.out.println(line);
    46                     if (line.equals("end")) break;
    47                 }
    48                 br.close();
    49                 pr.close();
    50             }
    51             catch(Exception ex)
    52             {
    53                 ex.printStackTrace();
    54             }
    55         }
    56     };
    57     
    58     thread1.setDaemon(true);
    59     thread2.setDaemon(true);
    60     thread1.start();
    61     thread2.start();
    62     thread1.join();
    63     thread2.join();
    64 }
  • 相关阅读:
    CSS外边距的合并
    四大主流浏览器内核
    ViewPort视口
    url、src、href定义以及使用区别
    Debug和Release区别
    基线概念
    浅谈C#循环控制流程语句(web前端基础)
    With you With me
    css元素内容基础
    年轻人有梦想,老人有回忆
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/3443255.html
Copyright © 2020-2023  润新知