当前位置:首页 > 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接口。

java如何使用多线程

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修饰方法或代码块实现同步。

java如何使用多线程

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()获取当前状态。

注意事项

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

分享给朋友:

相关文章

vue多线程实现run

vue多线程实现run

Vue 多线程实现 Worker 在 Vue 中实现多线程通常通过 Web Worker 完成。Web Worker 允许在后台线程中运行脚本,避免阻塞主线程。 创建 Worker 文件 新建一个…

如何使用react native

如何使用react native

安装开发环境 确保系统已安装Node.js(建议LTS版本)。通过npm或yarn全局安装React Native命令行工具: npm install -g react-native-cli # 或…

react如何使用插槽

react如何使用插槽

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

react中如何使用ajax

react中如何使用ajax

在React中使用AJAX React本身不提供AJAX功能,但可以通过以下几种方式实现AJAX请求: 使用原生fetch API fetch是现代浏览器内置的API,无需额外安装库即可使用: f…

react中如何使用swiper

react中如何使用swiper

安装 Swiper 依赖 在 React 项目中使用 Swiper 需要安装 Swiper 的核心库和 React 组件库。通过 npm 或 yarn 安装以下依赖: npm install swi…

react如何使用别的组件

react如何使用别的组件

使用组件的基础方法 在React中,使用其他组件通常通过导入和渲染实现。假设有一个名为Button的组件,文件路径为./components/Button。 // 导入组件 import But…