当前位置:首页 > Java

java多线程如何实现

2026-03-03 05:52:22Java

多线程的实现方式

在Java中,多线程可以通过继承Thread类或实现Runnable接口来实现。这两种方式各有优缺点,适用于不同的场景。

继承Thread类需要重写run方法,并通过调用start方法启动线程。这种方式简单直接,但由于Java不支持多重继承,如果类已经继承了其他类,就无法使用这种方式。

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

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

实现Runnable接口同样需要重写run方法,但需要通过Thread类的构造函数传入Runnable实例来启动线程。这种方式更加灵活,适用于需要实现多继承的场景。

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

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

线程池的使用

线程池是一种高效管理线程的机制,可以避免频繁创建和销毁线程的开销。Java提供了ExecutorService接口及其实现类来支持线程池。

创建固定大小的线程池可以使用Executors.newFixedThreadPool方法。提交任务到线程池后,线程池会自动分配线程执行任务。

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.submit(() -> {
                System.out.println("Task executed by " + Thread.currentThread().getName());
            });
        }
        executor.shutdown();
    }
}

线程同步与锁

多线程环境下,共享资源的访问可能导致数据不一致问题。Java提供了synchronized关键字和Lock接口来保证线程安全。

java多线程如何实现

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(counter.getCount());
    }
}

Lock接口提供了更灵活的锁机制,例如ReentrantLock。与synchronized相比,Lock支持尝试获取锁、超时等待等高级功能。

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

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

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

    public int getCount() {
        return count;
    }
}

线程间通信

线程间通信可以通过waitnotifynotifyAll方法实现。这些方法必须在synchronized块或方法内调用。

java多线程如何实现

wait使当前线程进入等待状态,释放锁。notifynotifyAll唤醒等待的线程。

class Message {
    private String message;
    private boolean empty = true;

    public synchronized String read() {
        while (empty) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        empty = true;
        notifyAll();
        return message;
    }

    public synchronized void write(String message) {
        while (!empty) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        empty = false;
        this.message = message;
        notifyAll();
    }
}

高级并发工具

Java并发包(java.util.concurrent)提供了许多高级并发工具,如CountDownLatchCyclicBarrierSemaphore等。

CountDownLatch允许一个或多个线程等待其他线程完成操作。

import java.util.concurrent.CountDownLatch;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(3);
        new Thread(() -> {
            System.out.println("Task 1 done");
            latch.countDown();
        }).start();
        new Thread(() -> {
            System.out.println("Task 2 done");
            latch.countDown();
        }).start();
        new Thread(() -> {
            System.out.println("Task 3 done");
            latch.countDown();
        }).start();
        latch.await();
        System.out.println("All tasks done");
    }
}

CyclicBarrier允许一组线程互相等待,达到某个公共屏障点后再继续执行。

import java.util.concurrent.CyclicBarrier;

public class Main {
    public static void main(String[] args) {
        CyclicBarrier barrier = new CyclicBarrier(3, () -> {
            System.out.println("All threads reached barrier");
        });
        new Thread(() -> {
            try {
                System.out.println("Thread 1 reached barrier");
                barrier.await();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                System.out.println("Thread 2 reached barrier");
                barrier.await();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                System.out.println("Thread 3 reached barrier");
                barrier.await();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }
}

分享给朋友:

相关文章

vue如何实现排序

vue如何实现排序

实现数组排序 在Vue中可以通过计算属性或方法对数组进行排序。使用JavaScript的sort()方法结合Vue的响应式特性实现动态排序。 data() { return { item…

vue如何实现uuid

vue如何实现uuid

生成 UUID 的方法 在 Vue 中生成 UUID 可以通过第三方库或原生 JavaScript 实现。以下是几种常见方法: 使用 uuid 库 安装 uuid 库: npm install u…

vue如何实现刷新

vue如何实现刷新

实现页面刷新的方法 在Vue中实现刷新功能可以通过以下几种方式实现: 使用location.reload() 直接调用浏览器的原生方法强制刷新整个页面: methods: { refr…

vue 如何实现返回

vue 如何实现返回

Vue 实现返回功能的方法 使用 router.go(-1) 在 Vue 中可以通过 Vue Router 的 go 方法实现返回上一页的功能。在需要触发返回的按钮或方法中调用 this.$route…

vue如何实现修改

vue如何实现修改

修改 Vue 组件或数据 在 Vue 中修改数据或组件状态通常涉及响应式数据的更新、组件方法的调用或状态管理工具的使用。以下是几种常见场景的实现方式: 修改响应式数据 Vue 的响应式系统会自动追踪…

vue路由如何实现

vue路由如何实现

vue路由的实现方法 Vue路由可以通过Vue Router库来实现。Vue Router是Vue.js官方的路由管理器,用于构建单页面应用(SPA)。 安装Vue Router 使用npm或yar…