当前位置:首页 > 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类提供了多种线程池的创建方法。

java 如何使用线程

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类可以为每个线程提供独立的变量副本,避免共享变量的线程安全问题。

java 如何使用线程

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方法设置。

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

分享给朋友:

相关文章

react如何使用图片

react如何使用图片

在React中使用图片的方法 静态图片导入 在React组件中可以直接通过import导入图片文件,这种方式适用于已知的静态资源。导入后,图片会被处理为模块,可通过src属性引用。 import R…

react中如何使用axios

react中如何使用axios

安装 axios 在项目中安装 axios 依赖: npm install axios # 或使用 yarn yarn add axios 引入 axios 在需要使用 axios 的组件或文件中引…

react如何使用layer弹出层

react如何使用layer弹出层

使用 React 实现弹出层(Layer) React 中实现弹出层可以通过自定义组件或第三方库(如 react-modal、@mui/material 的 Dialog)完成。以下是两种常见方法:…

react脚手架如何使用scss

react脚手架如何使用scss

使用SCSS/SASS在React脚手架中的配置方法 React脚手架(如Create React App)默认支持SCSS/SASS,只需简单配置即可使用。以下是具体实现方式: 安装SASS依赖…

vue项目中如何使用react组价

vue项目中如何使用react组价

在Vue项目中直接使用React组件需要借助特定的工具或库来实现跨框架兼容。以下是几种可行的方法: 通过vuera库集成 vuera是一个专门用于在Vue项目中嵌入React组件的库。安装依赖后,可…

react如何使用ant脚手架视频

react如何使用ant脚手架视频

使用 Ant Design Pro 脚手架创建 React 项目 Ant Design Pro 是 Ant Design 的脚手架工具,提供了一套开箱即用的企业级前端开发模板。以下是具体操作步骤:…