当前位置:首页 > 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修饰方法或代码块确保线程安全。

java线程如何使用

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实现生产者-消费者模式。

java线程如何使用

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类 为每个线程维护独立的变量副本。

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

分享给朋友:

相关文章

react如何使用redux

react如何使用redux

使用 Redux 在 React 中的应用 Redux 是一个状态管理库,通常与 React 结合使用以管理全局状态。以下是具体实现步骤: 安装依赖 确保项目中已安装 redux 和 react-r…

react router如何使用

react router如何使用

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

react如何使用agora

react如何使用agora

使用 React 集成 Agora 视频通话 SDK 安装 Agora SDK 在 React 项目中安装 Agora RTC SDK: npm install agora-rtc-sdk 初始化…

react如何使用插槽

react如何使用插槽

使用props.children实现基础插槽 React中插槽的核心是通过props.children传递子组件。父组件在标签内部放置的内容会自动成为children属性: // 父组件 <C…

web项目如何使用react

web项目如何使用react

使用 React 构建 Web 项目的关键步骤 环境准备 安装 Node.js 和 npm(或 yarn),确保开发环境支持现代 JavaScript。通过以下命令创建 React 项目: np…

react中如何使用onblur

react中如何使用onblur

在 React 中使用 onBlur 事件 onBlur 是当元素失去焦点时触发的事件。在 React 中,可以通过以下方式使用: 基础用法 <input type="text…