当前位置:首页 > Java

java 如何使用线程

2026-03-24 18:59:04Java

线程的基本使用

在Java中,线程可以通过继承Thread类或实现Runnable接口来创建。继承Thread类需要重写run方法,而实现Runnable接口需要实现run方法。

// 继承Thread类
class MyThread extends Thread {
    public void run() {
        System.out.println("Thread running");
    }
}

// 实现Runnable接口
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Runnable running");
    }
}

启动线程

通过调用start方法启动线程,而不是直接调用run方法。start方法会创建一个新的线程并执行run方法中的代码。

// 继承Thread类的方式
MyThread thread1 = new MyThread();
thread1.start();

// 实现Runnable接口的方式
Thread thread2 = new Thread(new MyRunnable());
thread2.start();

线程同步

多线程环境下,共享资源的访问可能会导致数据不一致。使用synchronized关键字可以确保同一时间只有一个线程访问共享资源。

class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

线程池的使用

Java提供了ExecutorService来管理线程池,避免频繁创建和销毁线程的开销。Executors类提供了多种线程池的创建方法。

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

线程间通信

waitnotify方法用于线程间的通信。wait使当前线程等待,notify唤醒等待中的线程。

class SharedResource {
    private boolean ready = false;

    public synchronized void waitForReady() throws InterruptedException {
        while (!ready) {
            wait();
        }
    }

    public synchronized void setReady() {
        ready = true;
        notifyAll();
    }
}

线程中断

通过调用interrupt方法可以中断线程。线程需要检查中断状态并做出响应。

class InterruptibleThread extends Thread {
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            System.out.println("Running");
        }
        System.out.println("Thread interrupted");
    }
}

InterruptibleThread thread = new InterruptibleThread();
thread.start();
thread.interrupt();

线程局部变量

ThreadLocal类可以为每个线程提供独立的变量副本,避免共享变量的线程安全问题。

ThreadLocal<String> threadLocal = ThreadLocal.withInitial(() -> "Initial Value");

System.out.println(threadLocal.get()); // Output: Initial Value
threadLocal.set("New Value");
System.out.println(threadLocal.get()); // Output: New Value

线程状态

线程的生命周期包括新建(NEW)、就绪(RUNNABLE)、运行(RUNNING)、阻塞(BLOCKED)、等待(WAITING)、超时等待(TIMED_WAITING)和终止(TERMINATED)状态。

Thread thread = new Thread(() -> {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
});
System.out.println(thread.getState()); // Output: NEW
thread.start();
System.out.println(thread.getState()); // Output: RUNNABLE

线程优先级

线程优先级范围从1(最低)到10(最高),默认优先级为5。优先级高的线程更有可能被调度执行。

Thread thread = new Thread(() -> System.out.println("Running"));
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();

守护线程

守护线程是为其他线程提供服务的线程,当所有非守护线程结束时,守护线程会自动终止。通过setDaemon方法设置。

java 如何使用线程

Thread daemonThread = new Thread(() -> {
    while (true) {
        System.out.println("Daemon thread running");
    }
});
daemonThread.setDaemon(true);
daemonThread.start();

分享给朋友:

相关文章

react如何使用axios

react如何使用axios

安装 Axios 在 React 项目中安装 Axios,可以通过 npm 或 yarn 进行安装: npm install axios 或 yarn add axios 导入 Axios 在需要…

react如何使用link

react如何使用link

使用 Link 组件进行页面导航 在 React 中,Link 是 react-router-dom 提供的组件,用于在单页应用(SPA)中实现客户端路由导航,避免页面刷新。 安装 react-…

react如何使用sass

react如何使用sass

安装 Sass 依赖 在 React 项目中安装 sass 作为开发依赖: npm install sass --save-dev 或使用 Yarn: yarn add sass --dev 创建…

react 如何使用fiber

react 如何使用fiber

使用 React Fiber 的方法 React Fiber 是 React 16 引入的重新实现的协调算法,用于优化渲染性能。以下是使用 Fiber 的方法。 理解 React Fiber 的核心…

react如何使用组件

react如何使用组件

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

内网如何使用react框架

内网如何使用react框架

内网使用React框架的部署与开发方法 在无外网连接的内网环境中使用React框架,需提前准备依赖包并配置本地开发环境。以下是具体实施方案: 离线安装Node.js和npm 从官网下载Node.js…