奇思妙想录 胜利者往往是从坚持最终五分钟的时间中得来成功。——牛顿
歌曲封面 未知作品

萌ICP备20248808号

津ICP备2023004371号-2

网站已运行 2 年 100 天 14 小时 17 分

Powered by Typecho & Sunny

3 online · 172 ms

Title

Thread类的基本用法笔记

IhaveBB

·

·

72次阅读
技术分享
Article
⚠️ 本文最后更新于2023年11月14日,已经过了343天没有更新,若内容或图片失效,请留言反馈
AI摘要:本文介绍了Java中Thread类的基本用法,包括线程创建、终止、等待、休眠和获取线程实例的方法。通过继承Thread类、实现Runnable接口、使用匿名内部类和lambda表达式创建线程。线程终止可以通过自定义标识符或interrupt()方法实现。线程等待使用join()方法,休眠使用sleep()方法。获取当前线程实例通过currentThread()方法。同时,文章还介绍了如何优雅地处理线程中断和InterruptedException异常。

Powered by AISummary.

Thread类的基本用法笔记

一.线程创建

1.继承Thread类

♾️ java 代码:
public class Main {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
        System.out.println("Main");
    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("MyThread");
    }
}

2.实现Runnable接口

♾️ java 代码:
public class Main {
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
        System.out.println("Main");
    }
}

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("MyRunnable");
    }
}

3.匿名内部类

♾️ java 代码:
public class Main {
    public static void main(String[] args) {
        Thread myThread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("myThread");
            }
        });
        myThread.start();
        System.out.println("Main");
    }
}

4.使用lambda表达式

♾️ java 代码:
public class Main {
    public static void main(String[] args) {
        Thread myThread = new Thread(() -> {
            System.out.println("myThread");
        });
        myThread.start();
        System.out.println("Main");
    }
}

二.线程终止

1.使用自定义的标识符来终止线程

♾️ java 代码:
public class ThreadTerminationExample1 {
    private static volatile boolean isRunning = true; // 自定义标识符

    public static void main(String[] args) throws InterruptedException {
        Thread myThread = new Thread(() -> {
            while (isRunning) {
                // 线程执行的代码
            }
            System.out.println("Thread terminated.");
        });
        myThread.start();

        // 模拟一段时间后停止线程
        Thread.sleep(1000);
        isRunning = false; // 设置标识符来终止线程
    }
}

2.使用interrupt() 终止线程

2.1理解线程中断

Java中的Thread类提供了一些更优雅的方法来操作线程的中断状态:

  • void interrupt(): 请求中断线程。
  • boolean isInterrupted(): 检查线程的中断状态。(通常不会使用)
  • static boolean interrupted(): 检查当前线程的中断状态,并清除中断状态。

2.2 检测中断状态

在线程内部,可以使用Thread.currentThread().isInterrupted()来检查线程的中断状态,例如:

♾️ java 代码:
while (!Thread.currentThread().isInterrupted()) {
    // 线程执行的代码
}

在这个循环中,线程会一直运行,直到中断状态变为true,即线程被请求中断。

2.3处理InterruptedException

在某些情况下,线程可能会等待某些条件的发生,例如使用Thread.sleep()Object.wait()。这些操作可能会抛出InterruptedException异常,因为其他线程调用了中断操作,希望中断当前线程的等待状态。

当捕获到InterruptedException时,通常的做法是在异常处理中重新设置线程的中断状态,以便线程能够正确地响应中断。示例如下:

♾️ java 代码:
try {
    // 在等待期间可能抛出InterruptedException
    // 处理等待逻辑
} catch (InterruptedException e) {
    e.printStackTrace();
    // 重新设置中断状态
    Thread.currentThread().interrupt();
}

2.4示例代码

♾️ java 代码:
public class ThreadInterruptExample {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("线程工作中");
                try {
                    Thread.sleep(1000); // 模拟线程工作
                } catch (InterruptedException e) {
                    System.out.println("线程收到中断请求");
                    Thread.currentThread().interrupt(); // 重新设置中断状态
                }
            }
            System.out.println("线程结束");
        });
        t.start();

        // 模拟一段时间后停止线程
        Thread.sleep(5000);
        System.out.println("t线程终止");
        t.interrupt();
    }
}

三.线程等待

1.join()方法

1.1理解join方法

  • void join(): 等待线程结束。
  • void join(long millis): 等待线程结束,最多等待millis毫秒。
  • void join(long millis, int nanos): 等待线程结束,最多等待millis毫秒 + nanos纳秒。

1.2使用join方法

♾️ java 代码:
public class ThreadJoinExample {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            System.out.println("线程运行中.");
        });
        thread.start();
        // 等待线程执行完毕
        thread.join();
        System.out.println("主方法运行中.");
    }
}

四.线程休眠

1.sleep()方法

1.1方法

  • public static void sleep(long millis) throws InterruptedException: 休眠当前线程millis毫秒。
  • public static void sleep(long millis, int nanos) throws InterruptedException: 更高精度的休眠。

1.2示例/结果

♾️ java 代码:
public class ThreadSleepExample {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            long begin = System.currentTimeMillis();
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            long end = System.currentTimeMillis();
            System.out.println(end - begin);
        });
        t.start();
    }
}
♾️ java 代码:
5000

2.TimeUtil休眠

2.1方法

TimeUnit.DAYS.sleep(1); // 天
TimeUnit.HOURS.sleep(1); // 小时
TimeUnit.MINUTES.sleep(1); // 分
TimeUnit.SECONDS.sleep(1); // 秒
TimeUnit.MILLISECONDS.sleep(1000); // 毫秒
TimeUnit.MICROSECONDS.sleep(1000); // 微秒
TimeUnit.NANOSECONDS.sleep(1000); // 纳秒

1.2代码示例

♾️ java 代码:
import java.util.concurrent.TimeUnit;

public class ThreadTimeUnitExample {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> {
            long begin = System.currentTimeMillis();
            try {
                TimeUnit.MICROSECONDS.sleep(1000); // 休眠1微秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            long end = System.currentTimeMillis();
            System.out.println(end - begin);
        });
        t.start();
    }
}

五.获取线程实例

1.currentThread()方法

1.1方法

public static Thread currentThread(); 返回当前对象的引用

1.2代码示例

♾️ java 代码:
public class ThreadInstanceExample {
    public static void main(String[] args) {
        Thread currentThread = Thread.currentThread();
        System.out.println("Current thread: " + currentThread.getName());
    }
}
现在已有 0 条评论,0 人点赞
Comment:共0条
发表
搜 索 消 息 足 迹
你还不曾留言过..
你还不曾留下足迹..
博主

哈喽大家好呀

本站已从原站:33mc.cn
迁移到本站:blog.nicebao.com
主域名变为:nicebao.com

不再显示
博主