Java并发执行举例

在Java中实现并发执行可以通过多种方式,最常见的方式包括使用线程、ExecutorServiceForkJoinPool等。以下是几种常用并发执行的示例:

1. 使用Thread

这是Java中最基础的并发实现,通过创建一个继承自Thread的类或实现Runnable接口来定义任务,并启动线程。

class MyTask extends Thread {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " is executing task.");
    }
}

public class Main {
    public static void main(String[] args) {
        MyTask task1 = new MyTask();
        MyTask task2 = new MyTask();

        task1.start();
        task2.start();
    }
}

2. 使用Runnable接口

Runnable接口更灵活,因为可以让任务类继承其他类,同时实现并发任务。

class MyRunnableTask implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " is executing task.");
    }
}

public class Main {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new MyRunnableTask());
        Thread thread2 = new Thread(new MyRunnableTask());

        thread1.start();
        thread2.start();
    }
}

3. 使用ExecutorService

ExecutorService是Java中用于管理线程池的接口,能够更高效地执行并发任务,适合管理大量并发任务。

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

public class Main {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        Runnable task1 = () -> {
            System.out.println(Thread.currentThread().getName() + " is executing task 1.");
        };

        Runnable task2 = () -> {
            System.out.println(Thread.currentThread().getName() + " is executing task 2.");
        };

        executor.submit(task1);
        executor.submit(task2);

        executor.shutdown(); // 关闭线程池
    }
}

4. 使用CallableFuture

Callable接口允许任务返回结果,而Future可以用于获取结果或控制任务的执行状态。

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

public class Main {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();

        Callable<Integer> task = () -> {
            System.out.println(Thread.currentThread().getName() + " is executing task.");
            return 123;
        };

        Future<Integer> future = executor.submit(task);

        // 阻塞等待结果
        Integer result = future.get();
        System.out.println("Task result: " + result);

        executor.shutdown();
    }
}

5. 使用ForkJoinPool

ForkJoinPool是专门用于并行处理任务的线程池,特别适合用于递归任务。

import java.util.concurrent.RecursiveTask;
import java.util.concurrent.ForkJoinPool;

class FibonacciTask extends RecursiveTask<Integer> {
    private final int n;

    public FibonacciTask(int n) {
        this.n = n;
    }

    @Override
    protected Integer compute() {
        if (n <= 1) {
            return n;
        }
        FibonacciTask f1 = new FibonacciTask(n - 1);
        FibonacciTask f2 = new FibonacciTask(n - 2);
        f1.fork();
        return f2.compute() + f1.join();
    }
}

public class Main {
    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool();
        FibonacciTask task = new FibonacciTask(10);

        Integer result = pool.invoke(task);
        System.out.println("Fibonacci result: " + result);
    }
}

这些例子展示了不同的Java并发编程方式,使用场景可以根据实际需求选择合适的实现方式。例如,对于简单的并发任务,ThreadRunnable就足够了;而对于复杂的任务,ExecutorServiceForkJoinPool可能会更高效。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天天进步2015

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值