thread类_想在面试中脱颖而出,教你几个Thread的使用技巧

点击蓝字

关注我们

46d8799c28c30d0d94d4a80094eba8cc.png

fd751af154800cf6702a5958c765dfd3.png 祝愿你能拿到令你心动的offerfd751af154800cf6702a5958c765dfd3.png


在本文中,我们将通过实例学习重要的Thread类中的API/方法。

Thread类方法列表

该类图显示了一个java.lang.Thread类API/Methods的列表。

Thread类方法使用示例

我们来演示一下java.lang.Thread类的几个重要方法的用法。

Thread.sleep() 方法

Thread.sleep 导致当前线程在指定时间内暂停执行。这是一种有效的手段,可以让应用程序的其他线程或计算机系统上可能运行的其他应用程序获得处理器时间。

Thread.sleep()方法示例

在这个例子中,我们创建并启动了两个线程thread1thread2。请注意,我们在这个例子中使用了sleep()方法的两个重载版本:

Thread.sleep(1000);Thread.sleep(1000, 500);/** * thread sleep method examples * @author Noseparte * */public class ThreadSleepExample {      public static void main(final String[] args) {          System.out.println("Thread main started");          final Thread thread1 = new Thread(new WorkerThread());          thread1.setName("WorkerThread 1");          final Thread thread2 = new Thread(new WorkerThread());          thread1.setName("WorkerThread 2");          thread1.start();          thread2.start();          System.out.println("Thread main ended");      }}class WorkerThread implements Runnable {        @Override        public void run() {            for (int i = 0; i < 5; i++) {                try {                    Thread.sleep(1000);                    Thread.sleep(1000, 500);                    System.out.println("[" + Thread.currentThread().getName() + "] Message " + i);                } catch (final InterruptedException e) {                    e.printStackTrace();                }            }       }}

Output:

Thread main startedThread main ended[WorkerThread 2] Message 0[Thread-1] Message 0[WorkerThread 2] Message 1[Thread-1] Message 1[WorkerThread 2] Message 2[Thread-1] Message 2[WorkerThread 2] Message 3[Thread-1] Message 3[WorkerThread 2] Message 4[Thread-1] Message 4

请注意,sleep()方法会抛出InterruptedException异常,当另一个线程在睡眠活动时中断当前线程。

Thread.join() 方法

join()方法会等待一个线程死亡。换句话说,它使当前正在运行的线程停止执行,直到与它接合的线程完成任务。

线程join()方法示例。首先,我们将创建一个任务,它将计算1-5个数字的总和(在for循环中维护)。在主线程中,让我们创建4个任务:

final Task task1 = new Task(500l);final Task task2 = new Task(1000l);final Task task3 = new Task(2000l);final Task task4 = new Task(50l);

现在,让我们创建4个线程来运行以上4个任务:

final Thread thread1 = new Thread(task1); final Thread thread2 = new Thread(task2);final Thread thread3 = new Thread(task3);final Thread thread4 = new Thread(task4);

给每个人指定名字,并开始所有的4个线程:

thread1.setName("thread-1");thread2.setName("thread-2");thread3.setName("thread-3");thread4.setName("thread-4");thread1.start();thread2.start();thread3.start();thread4.start();

在这个例子中,当目标线程完成求和时,调用者线程(main)会被唤醒,并调用task.getSum()方法,由于目标线程已经完成了工作,因此该方法肯定会包含总和。

task4的睡眠时间较小,因此它比其他线程先完成总和。因此,主线程调用了thread4.join(),但由于thread4已经完成了工作,所以立即返回其执行。

/** * This class demonstrate the how join method works with an example.  * @author Noseparte * */public class ThreadJoinExample {    public static void main(final String[] args) throws InterruptedException {        System.out.println("Thread main started");         final Task task1 = new Task(500l);       final Task task2 = new Task(1000l);       final Task task3 = new Task(2000l);       final Task task4 = new Task(50l);       final Thread thread1 = new Thread(task1);        final Thread thread2 = new Thread(task2);       final Thread thread3 = new Thread(task3);       final Thread thread4 = new Thread(task4);        thread1.setName("thread-1");       thread2.setName("thread-2");       thread3.setName("thread-3");       thread4.setName("thread-4");       thread1.start();       thread2.start();       thread3.start();       thread4.start();         System.out.println("[" + Thread.currentThread().getName() + "] waiting for " + thread1.getName());       thread1.join();       System.out.println(thread1.getName() + " finished! Result: " + task1.getSum());         System.out.println("[" + Thread.currentThread().getName() + "] waiting for " + thread2.getName());       thread2.join();       System.out.println(thread2.getName() + " finished! Result: " + task2.getSum());        System.out.println("[" + Thread.currentThread().getName() + "] waiting for " + thread3.getName());      thread3.join();      System.out.println(thread3.getName() + " finished! Result: " + task3.getSum());       // As thread-4 already finished (smaller sleep time), the join call only immediately     // returns the control to the caller thread     System.out.println("[" + Thread.currentThread().getName() + "] waiting for " + thread4.getName());     thread4.join();     System.out.println(thread4.getName() + " finished! Result: " + task4.getSum());       System.out.println("Thread main finished");   }}class Task implements Runnable {     private long sleep;      private int sum;      public Task(final long sleep) {         this.sleep = sleep;     }      @Override     public void run() {         for (int i = 1; i <= 5; i++) {              System.out.println("[" + Thread.currentThread().getName() + "] Adding " + i);              sum += i;              try {                  Thread.sleep(sleep);              } catch (final InterruptedException e) {                  e.printStackTrace();              }         }     }      public int getSum() {         return this.sum;     }}

Output:

Thread main started[thread-1] Adding 1[thread-2] Adding 1[thread-3] Adding 1[main] waiting for thread-1[thread-4] Adding 1[thread-4] Adding 2[thread-4] Adding 3[thread-4] Adding 4[thread-4] Adding 5[thread-1] Adding 2[thread-1] Adding 3[thread-2] Adding 2[thread-1] Adding 4[thread-1] Adding 5[thread-3] Adding 2[thread-2] Adding 3thread-1 finished! Result: 15[main] waiting for thread-2[thread-2] Adding 4[thread-2] Adding 5[thread-3] Adding 3thread-2 finished! Result: 15[main] waiting for thread-3[thread-3] Adding 4[thread-3] Adding 5thread-3 finished! Result: 15[main] waiting for thread-4thread-4 finished! Result: 15Thread main finished

注意,输出,main()线程最后完成了它的执行。试着通过查看一个输出来理解这个例子。

join()方法会抛出一个InterruptedException--如果有线程中断了当前线程。当这个异常被抛出时,当前线程的中断状态被清除。

Thread.interrupt() 方法

中断是对线程的一种指示,表明它应该停止正在做的事情,做别的事情。线程对中断的具体响应方式由程序员决定,但线程终止的情况非常普遍。

java.lang Thread类提供了三个interrupt()方法来正常工作Interrupts。

  1. void interrupt()--中断这个线程。

  2. static boolean interrupted()--测试当前线程是否被中断。

  3. 3.boolean isInterrupted() - 测试该线程是否被中断。

Thread.interrupt()方法示例:

public class TerminateTaskUsingThreadAPI {     public static void main(final String[] args) {System.out.println("Thread main started");        final Task task = new Task();         final Thread thread = new Thread(task);         thread.start();         thread.interrupt();         System.out.println("Thread main finished");      }}class Task implements Runnable {     @Override     public void run() {      for (int i = 0; i < 5; i++) {       System.out.println("[" + Thread.currentThread().getName() + "] Message " + i);       if (Thread.interrupted()) {        System.out.println("This thread was interruped by someone calling this     Thread.interrupt()");        System.out.println("Cancelling task running in thread " +             Thread.currentThread().getName());        System.out.println("After Thread.interrupted() call, JVM reset the interrupted value to: " + Thread.interrupted());        break;       }      }     }}

Output:

Thread main startedThread main finished[Thread-0] Message 0This thread was interruped by someone calling this Thread.interrupt()Cancelling task running in thread Thread-0After Thread.interrupted() call, JVM reset the interrupted value to: false

注意这里的任务是被终止的,而不是线程。

Thread.isAlive() 方法

java.lang.Thread类提供了isAlive()方法来测试这个线程是否活着。如果一个线程已经启动并且还没有死亡,那么这个线程就是活着的。

线程isAlive方法示例:

  1. 创建俩个线程:

final Thread thread1 = new Thread(new MyTask());final Thread thread2 = new Thread(new MyTask());
  1. 在用start()方法启动线程之前,只需打印检查线程是否活着。

System.out.println("Thread1 is alive? " + thread1.isAlive());System.out.println("Thread2 is alive? " + thread2.isAlive());
  1. 启动线程,再检查一下线程是否存活。

thread1.start();thread2.start();while (thread1.isAlive() || thread2.isAlive()) {     System.out.println("Thread1 is alive? " + thread1.isAlive());     System.out.println("Thread2 is alive? " + thread2.isAlive());     Thread.sleep(500l);}

让我们把所有完整的程序放在一起。:

public class CheckIfThreadIsAliveUsingThreadAPI { public static void main(final String[] args) throws InterruptedException {      System.out.println("Thread main started");      final Thread thread1 = new Thread(new MyTask());      final Thread thread2 = new Thread(new MyTask());      System.out.println("Thread1 is alive? " + thread1.isAlive());      System.out.println("Thread2 is alive? " + thread2.isAlive());      thread1.start();      thread2.start();      while (thread1.isAlive() || thread2.isAlive()) {       System.out.println("Thread1 is alive? " + thread1.isAlive());       System.out.println("Thread2 is alive? " + thread2.isAlive());       Thread.sleep(500l);      }      System.out.println("Thread1 is alive? " + thread1.isAlive());      System.out.println("Thread2 is alive? " + thread2.isAlive());        System.out.println("Thread main finished");     }}class MyTask implements Runnable { @Override public void run() {  for (int i = 0; i < 5; i++) {   System.out.println("[" + Thread.currentThread().getName() + "] Message " + i);   try {    Thread.sleep(200);   } catch (final InterruptedException e) {    e.printStackTrace();   }  } }}

Output:

Thread main startedThread1 is alive? falseThread2 is alive? falseThread1 is alive? trueThread2 is alive? true[Thread-0] Message 0[Thread-1] Message 0[Thread-1] Message 1[Thread-0] Message 1[Thread-1] Message 2[Thread-0] Message 2Thread1 is alive? trueThread2 is alive? true[Thread-0] Message 3[Thread-1] Message 3[Thread-1] Message 4[Thread-0] Message 4Thread1 is alive? falseThread2 is alive? falseThread main finished

Thread.setPriority() 方法

每个线程都有一个优先级。优先级用1到10之间的数字表示。在大多数情况下,线程调度器根据线程的优先级来调度线程(称为抢先调度)。但这并不能保证,因为它选择哪种调度方式取决于JVM规范。

Thread类中定义了三个常量。

  1. public static int MIN_PRIORITY

  2. public static int NORM_PRIORITY 静态的NORM_PRIORITY

  3. public static int MAX_PRIORITY 线程的默认优先级为5(NORM_PRIORITY)。MIN_PRIORITY的值是1,MAX_PRIORITY的值是10。

为线程设置优先级 示例

public class ThreadPriorityExample {     public static void main(final String[] args) {      final Runnable runnable = () -> {        System.out.println("Running thread name : " +     Thread.currentThread().getName() +        " and it's priority : " + Thread.currentThread().getPriority());     };        final Thread thread1 = new Thread(runnable);      final Thread thread2 = new Thread(runnable);      final Thread thread3 = new Thread(runnable);      final Thread thread4 = new Thread(runnable);      thread1.setPriority(Thread.MIN_PRIORITY);      thread2.setPriority(Thread.NORM_PRIORITY);      thread3.setPriority(Thread.MAX_PRIORITY);      thread4.setPriority(2);        thread1.start();      thread2.start();      thread3.start();      thread4.start();     }}

Output:

Running thread name : Thread-0 and it's priority : 1Running thread name : Thread-1 and it's priority : 5Running thread name : Thread-2 and it's priority : 10Running thread name : Thread-3 and it's priority : 2

Thread.setName() 方法

java.lang.Thread类提供了改变和获取线程名称的方法。默认情况下,每个线程都有一个名字,即thread-0、thread-1等。我们可以通过使用setName()方法来改变线程的名称。下面给出了setName()和getName()方法的语法。

  • public String getName():用于返回线程的名称。

  • 公共void setName(String name) 用于更改线程的名称。

Thread类提供了一个静态的currentThread()--返回一个对当前执行的线程对象的引用。

命名一个线程实例:

/** *  Thread naming example using Thread class. *  @author Noseparte **/public class ThreadExample {  public static void main(final String[] args) {    System.out.println("Thread main started");  final Thread thread1 = new WorkerThread();  thread1.setName("WorkerThread1");    final Thread thread2 = new WorkerThread();  thread2.setName("WorkerThread2");    final Thread thread3 = new WorkerThread();  thread3.setName("WorkerThread3");    final Thread thread4 = new WorkerThread();  thread4.setName("WorkerThread4");    thread1.start();  thread2.start();  thread3.start();  thread4.start();    System.out.println("Thread main finished"); }}class WorkerThread extends Thread {  @Override public void run() {  System.out.println("Thread Name :: " + Thread.currentThread().getName()); }}

Output:

Thread main startedThread Name :: WorkerThread1Thread Name :: WorkerThread2Thread Name :: WorkerThread3Thread main finishedThread Name :: WorkerThread4

65b54ba9b9a5d4fc4cecb83b49114924.png

7efacdaf-0833-eb11-8da9-e4434bdf6706.svg

球分享

7ffacdaf-0833-eb11-8da9-e4434bdf6706.svg

球点赞

cc45a852c18366e7159fa059667d1b84.gif

球在看

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
完整版:https://download.csdn.net/download/qq_27595745/89522468 【课程大纲】 1-1 什么是java 1-2 认识java语言 1-3 java平台的体系结构 1-4 java SE环境安装和配置 2-1 java程序简介 2-2 计算机的程序 2-3 java程序 2-4 java库组织结构和文档 2-5 java虚拟机简介 2-6 java的垃圾回收器 2-7 java上机练习 3-1 java语言基础入门 3-2 数据的分 3-3 标识符、关键字和常量 3-4 运算符 3-5 表达式 3-6 顺序结构和选择结构 3-7 循环语句 3-8 跳转语句 3-9 MyEclipse工具介绍 3-10 java基础知识章节练习 4-1 一维数组 4-2 数组应用 4-3 多维数组 4-4 排序算法 4-5 增强for循环 4-6 数组和排序算法章节练习 5-0 抽象和封装 5-1 面向过程的设计思 5-2 面向对象的设计思 5-3 抽象 5-4 封装 5-5 属性 5-6 方法的定义 5-7 this关键字 5-8 javaBean 5-9 包 package 5-10 抽象和封装章节练习 6-0 继承和多态 6-1 继承 6-2 object 6-3 多态 6-4 访问修饰符 6-5 static修饰符 6-6 final修饰符 6-7 abstract修饰符 6-8 接口 6-9 继承和多态 章节练习 7-1 面向对象的分析与设计简介 7-2 对象模型建立 7-3 之间的关系 7-4 软件的可维护与复用设计原则 7-5 面向对象的设计与分析 章节练习 8-1 内部与包装器 8-2 对象包装器 8-3 装箱和拆箱 8-4 练习题 9-1 常用介绍 9-2 StringBuffer和String Builder 9-3 Rintime使用 9-4 日期简介 9-5 java程序国际化的实现 9-6 Random和Math 9-7 枚举 9-8 练习题 10-1 java异常处理 10-2 认识异常 10-3 使用try和catch捕获异常 10-4 使用throw和throws引发异常 10-5 finally关键字 10-6 getMessage和printStackTrace方法 10-7 异常分 10-8 自定义异常 10-9 练习题 11-1 Java集合框架和泛型机制 11-2 Collection接口 11-3 Set接口实现 11-4 List接口实现 11-5 Map接口 11-6 Collections 11-7 泛型概述 11-8 练习题 12-1 多线程 12-2 线程的生命周期 12-3 线程的调度和优先级 12-4 线程的同步 12-5 集合的同步问题 12-6 用Timer调度任务 12-7 练习题 13-1 Java IO 13-2 Java IO原理 13-3 流的结构 13-4 文件流 13-5 缓冲流 13-6 转换流 13-7 数据流 13-8 打印流 13-9 对象流 13-10 随机存取文件流 13-11 zip文件流 13-12 练习题 14-1 图形用户界面设计 14-2 事件处理机制 14-3 AWT常用组件 14-4 swing简介 14-5 可视化开发swing组件 14-6 声音的播放和处理 14-7 2D图形的绘制 14-8 练习题 15-1 反射 15-2 使用Java反射机制 15-3 反射与动态代理 15-4 练习题 16-1 Java标注 16-2 JDK内置的基本标注型 16-3 自定义标注型 16-4 对标注进行标注 16-5 利用反射获取标注信息 16-6 练习题 17-1 顶目实战1-单机版五子棋游戏 17-2 总体设计 17-3 代码实现 17-4 程序的运行与发布 17-5 手动生成可执行JAR文件 17-6 练习题 18-1 Java数据库编程 18-2 JDBC和接口 18-3 JDBC操作SQL 18-4 JDBC基本示例 18-5 JDBC应用示例 18-6 练习题 19-1 。。。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值