当前位置:首页 > Java

java如何使用多线程

2026-03-04 01:21:51Java

多线程的基本概念

Java多线程允许程序同时执行多个任务,提高资源利用率和程序效率。线程是轻量级的进程,共享同一进程的资源。

创建线程的方法

继承Thread类
通过继承Thread类并重写run()方法实现多线程。

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("Thread running by extending Thread class");
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start(); // 启动线程
    }
}

实现Runnable接口
更推荐的方式是实现Runnable接口,避免单继承的限制。

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("Thread running by implementing Runnable");
    }
}

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyRunnable());
        thread.start();
    }
}

使用Lambda表达式(Java 8+)
简化代码,直接通过Lambda表达式实现Runnable接口。

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println("Thread running via Lambda");
        });
        thread.start();
    }
}

线程池管理

使用ExecutorService管理线程池,避免频繁创建和销毁线程的开销。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 5; i++) {
            executor.execute(() -> {
                System.out.println("Task executed by thread pool");
            });
        }
        executor.shutdown(); // 关闭线程池
    }
}

线程同步与锁

多线程共享资源时需同步,避免竞态条件。

synchronized关键字
通过synchronized修饰方法或代码块实现同步。

class Counter {
    private int count = 0;

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

    public int getCount() {
        return count;
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Count: " + counter.getCount());
    }
}

ReentrantLock
ReentrantLock提供更灵活的锁机制。

import java.util.concurrent.locks.ReentrantLock;

class Counter {
    private int count = 0;
    private ReentrantLock lock = new ReentrantLock();

    public void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }
}

线程间通信

通过wait()notify()notifyAll()实现线程协作。

class SharedResource {
    private boolean ready = false;

    public synchronized void produce() {
        ready = true;
        notify(); // 通知等待的线程
    }

    public synchronized void consume() throws InterruptedException {
        while (!ready) {
            wait(); // 等待条件满足
        }
        System.out.println("Resource consumed");
    }
}

线程状态与生命周期

线程状态包括NEWRUNNABLEBLOCKEDWAITINGTIMED_WAITINGTERMINATED。可通过Thread.getState()获取当前状态。

java如何使用多线程

注意事项

  • 避免死锁:确保锁的获取和释放顺序一致。
  • 减少锁粒度:缩小同步块范围以提高性能。
  • 使用线程安全集合:如ConcurrentHashMapCopyOnWriteArrayList等。

分享给朋友:

相关文章

react路由如何使用

react路由如何使用

React 路由的基本使用 React 路由通常通过 react-router-dom 库实现,用于管理单页面应用(SPA)中的页面导航。 安装 react-router-dom: npm ins…

react 如何使用canvas

react 如何使用canvas

使用 Canvas 在 React 中的方法 基本用法 在 React 中使用 canvas 需要通过 useRef 或 createRef 获取 DOM 节点。以下是一个简单的示例: im…

react如何使用webview

react如何使用webview

使用 React 实现 WebView 的方法 在 React 中,可以通过不同的方式实现 WebView 功能,具体取决于开发环境(如 React Native 或 Web 应用)。以下是常见的实现…

react如何使用axios

react如何使用axios

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

react 如何使用fiber

react 如何使用fiber

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

react redux如何使用

react redux如何使用

安装依赖 确保项目已安装 React 和 Redux 相关库。通过以下命令安装核心依赖: npm install redux react-redux @reduxjs/toolkit 创建 Stor…