当前位置:首页 > 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接口来保证线程安全。

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块或方法内调用。

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允许一组线程互相等待,达到某个公共屏障点后再继续执行。

java多线程如何实现

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 方法 在 Vue 中可以通过 window.scrollTo 或 Element.scrollIntoView 实现滚动。例如,滚动到页面顶部:…

vue如何实现id

vue如何实现id

在 Vue 中实现 ID 绑定 Vue 提供了多种方式为元素或组件绑定唯一的 ID,可以根据具体需求选择合适的方法。 方法一:使用 v-bind 绑定静态或动态 ID <template&g…

vue项目如何实现

vue项目如何实现

安装Vue.js 通过npm或yarn安装Vue.js。确保Node.js环境已配置完成。 npm install vue # 或 yarn add vue 创建Vue项目 使用Vue CLI工具快…

vue如何实现截图

vue如何实现截图

Vue 实现截图的方法 在 Vue 中实现截图功能可以通过多种方式完成,以下是几种常见的实现方法: 使用 html2canvas 库 html2canvas 是一个流行的 JavaScript 库,…

vue如何实现级联

vue如何实现级联

实现级联选择器的基本方法 在Vue中实现级联选择器通常使用现成的组件库或自定义组件。以下是两种常见方式: 使用Element UI的Cascader组件 安装Element UI后,直接使用el-c…

vue如何实现confirm

vue如何实现confirm

Vue 实现 Confirm 弹窗的方法 在 Vue 中实现确认弹窗(Confirm)可以通过多种方式,以下是几种常见的方法: 使用浏览器原生 confirm 最简单的实现方式是直接调用浏览器的原生…