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

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

java多线程如何实现

分享给朋友:

相关文章

vue如何实现mvvm

vue如何实现mvvm

Vue 实现 MVVM 的核心机制 Vue 的 MVVM(Model-View-ViewModel)实现依赖于数据绑定和响应式系统,通过以下核心机制完成: 数据劫持(响应式系统) Vue 使用 Ob…

vue如何实现放大缩小

vue如何实现放大缩小

Vue 实现放大缩小功能 在 Vue 中实现放大缩小功能可以通过多种方式实现,以下介绍几种常见的方法: 使用 CSS transform 缩放 通过绑定 CSS 的 transform: scale…

php如何实现静态化

php如何实现静态化

PHP 实现静态化的方法 使用 ob_start() 和 ob_get_contents() 利用 PHP 的输出缓冲功能捕获动态生成的页面内容,将其保存为静态文件。这种方法适用于内容不频繁变化的页面…

vue如何实现高亮

vue如何实现高亮

实现文本高亮的方法 在Vue中实现文本高亮通常可以通过以下几种方式完成: 使用v-html指令结合字符串替换 通过将需要高亮的文本部分替换为HTML标签(如<span class="high…

java是如何实现跨平台的

java是如何实现跨平台的

Java 跨平台的实现原理 Java 实现跨平台的核心机制基于 “一次编写,到处运行” 的理念,主要通过以下技术实现: 字节码与 JVM Java 源代码编译后生成字节码(.class 文件),而非…

java如何实现多继承

java如何实现多继承

在Java中,由于语言设计本身不支持多继承(即一个类不能直接继承多个父类),但可以通过以下方式间接实现类似多继承的效果: 使用接口实现多继承 接口允许一个类实现多个接口,从而继承多个抽象行为。接口中…