当前位置:首页 > Java

java线程如何使用

2026-04-09 05:32:51Java

线程的基本概念

Java线程是程序执行的最小单元,允许并发执行多个任务。每个线程都有自己的调用栈和程序计数器,共享进程的堆和方法区资源。

创建线程的方法

继承Thread类 通过继承Thread类并重写run()方法创建线程。实例化后调用start()方法启动线程。

class MyThread extends Thread {
    public void run() {
        System.out.println("Thread running");
    }
}
MyThread thread = new MyThread();
thread.start();

实现Runnable接口 实现Runnable接口的run()方法,将实例作为参数传递给Thread构造函数。

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Runnable running");
    }
}
Thread thread = new Thread(new MyRunnable());
thread.start();

使用Lambda表达式 Java 8后可通过Lambda简化Runnable实现。

Thread thread = new Thread(() -> {
    System.out.println("Lambda thread running");
});
thread.start();

线程的生命周期

线程具有以下状态:

  • NEW:创建但未启动
  • RUNNABLE:可运行或正在运行
  • BLOCKED:等待监视器锁
  • WAITING:无限期等待其他线程操作
  • TIMED_WAITING:有限时间等待
  • TERMINATED:执行完成

线程同步与锁

synchronized关键字 使用synchronized修饰方法或代码块确保线程安全。

public synchronized void synchronizedMethod() {
    // 线程安全代码
}

public void method() {
    synchronized(this) {
        // 同步代码块
    }
}

ReentrantLock类 提供更灵活的锁机制,需手动释放锁。

ReentrantLock lock = new ReentrantLock();
lock.lock();
try {
    // 临界区代码
} finally {
    lock.unlock();
}

线程间通信

wait()和notify() 通过Object类的wait()notify()实现线程间协调。

synchronized(sharedObject) {
    while(conditionNotMet) {
        sharedObject.wait();
    }
    // 执行操作
    sharedObject.notifyAll();
}

BlockingQueue 使用BlockingQueue实现生产者-消费者模式。

BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
// 生产者
queue.put(1);
// 消费者
int value = queue.take();

线程池的使用

Executor框架 通过Executors工厂类创建线程池。

ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
    System.out.println("Task executed by thread pool");
});
executor.shutdown();

ThreadPoolExecutor 自定义线程池参数。

ThreadPoolExecutor executor = new ThreadPoolExecutor(
    2, 4, 60, TimeUnit.SECONDS,
    new ArrayBlockingQueue<>(10)
);
executor.execute(task);

线程中断处理

interrupt()方法 通过interrupt()请求中断线程,需检查中断状态。

Thread thread = new Thread(() -> {
    while(!Thread.currentThread().isInterrupted()) {
        // 执行任务
    }
});
thread.start();
thread.interrupt();

线程局部变量

ThreadLocal类 为每个线程维护独立的变量副本。

java线程如何使用

ThreadLocal<String> threadLocal = ThreadLocal.withInitial(() -> "Initial");
threadLocal.set("Thread-specific value");
String value = threadLocal.get();

分享给朋友:

相关文章

react如何使用函数

react如何使用函数

使用函数组件的基本语法 在React中,函数组件是通过JavaScript函数定义的组件。函数接收props作为参数,并返回React元素。 function Welcome(props) {…

react router如何使用

react router如何使用

React Router 的基本使用 安装 React Router 库,使用 npm 或 yarn 进行安装: npm install react-router-dom 配置路由 在应用的入口文件…

react 如何使用axios

react 如何使用axios

安装 axios 在 React 项目中安装 axios 依赖包: npm install axios # 或 yarn add axios 引入 axios 在需要发送 HTTP 请求的组件或文件…

react如何使用less

react如何使用less

使用 Less 在 React 项目中 要在 React 项目中使用 Less,需要安装相关依赖并配置构建工具(如 Webpack 或 Create React App 的配置覆盖)。以下是具体方法:…

react如何使用组件

react如何使用组件

使用组件的基本方法 在React中,组件是构建用户界面的核心单元。组件分为函数组件和类组件两种形式。 函数组件示例 function Greeting(props) { return <…

react中如何使用echarts

react中如何使用echarts

安装 ECharts 依赖 在 React 项目中安装 ECharts 核心库和 React 封装库。使用 npm 或 yarn 安装: npm install echarts echarts-fo…