java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java Thread 类用法

Thread 类的基本用法、Java 线程的几种状态分析

作者:我会替风去

Java中的Thread类是多线程编程的核心,Java线程共有6种状态,包括NEW、RUNNABLE、BLOCKED、WAITING、TIMED_WAITING和TERMINATED,接下来通过本文给大家介绍Thread 类的基本用法、Java 线程的几种状态,感兴趣的朋友跟随小编一起看看吧

在Java中,Thread类是多线程编程的核心。

线程创建 (Thread Creation)

// 自定义线程类继承Thread
class MyThread extends Thread {
    // 重写run(),定义线程执行逻辑
    @Override
    public void run() {
        System.out.println("子线程执行:" + Thread.currentThread().getName());
    }
}

// 使用
public class Demo {
    public static void main(String[] args) {
        MyThread t = new MyThread();
        t.start(); // 3. 调用start()启动线程(不能直接调用run())
    }
}
// 实现Runnable接口
class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("子线程执行:" + Thread.currentThread().getName());
    }
}

// 使用
public class Demo {
    public static void main(String[] args) {
        // 把Runnable实例传给Thread
        Thread t = new Thread(new MyRunnable());
        t.start(); // 启动线程
    }
}

线程中断 (Thread Interruption)

Thread t = new Thread(() -> {
    while (!Thread.currentThread().isInterrupted()) { // 检测中断状态
        System.out.println("线程运行中...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // 捕获中断异常后,中断状态会被清除,需手动终止循环
            System.out.println("线程被中断");
            Thread.currentThread().interrupt(); // 重新标记中断(可选)
            break;
        }
    }
});
t.start();
// 主线程1秒后中断子线程
Thread.sleep(1000);
t.interrupt();

线程等待 (Thread Join)

Thread t = new Thread(() -> {
    System.out.println("子线程开始执行");
    try { Thread.sleep(2000); } catch (InterruptedException e) {}
    System.out.println("子线程执行完毕");
});
t.start();

// 主线程等待t执行完(最多等3秒)
t.join(3000); 
System.out.println("主线程继续执行");

线程休眠 (Thread Sleep)

System.out.println("开始休眠");
try {
    Thread.sleep(2000); // 当前线程休眠2秒
} catch (InterruptedException e) {
    e.printStackTrace();
}
System.out.println("休眠结束");

获取线程实例 (Get Current Instance)

// 获取当前线程(这里是main线程)
Thread mainThread = Thread.currentThread();
System.out.println("当前线程名:" + mainThread.getName()); // 输出"main"

// 子线程实例
Thread t = new Thread(() -> {
    Thread current = Thread.currentThread();
    System.out.println("子线程名:" + current.getName()); // 输出"Thread-0"
});
t.start();

Java线程的几种状态

线程状态一共有几种?

每种状态的含义与切换条件

到此这篇关于Thread 类的基本用法、Java 线程的几种状态分析的文章就介绍到这了,更多相关Java Thread 类用法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文