Java线程任务案例如何提交执行

wen java案例 27

本文目录导读:

Java线程任务案例如何提交执行

  1. 使用 Thread 类直接创建
  2. 使用线程池 (ExecutorService)
  3. 完整的生产者-消费者案例
  4. 使用 CompletableFuture 实现异步编排
  5. 定时任务执行
  6. 提交任务的常用方法对比

我来介绍Java中提交和执行线程任务的几种主要方式和案例。

使用 Thread 类直接创建

public class ThreadExample {
    public static void main(String[] args) {
        // 方式1:继承Thread类
        Thread thread1 = new MyThread("线程1");
        thread1.start();  // 提交执行
        // 方式2:实现Runnable接口
        Thread thread2 = new Thread(new MyRunnable("线程2"));
        thread2.start();  // 提交执行
        // 方式3:Lambda表达式
        Thread thread3 = new Thread(() -> {
            System.out.println("Lambda线程执行: " + Thread.currentThread().getName());
        }, "线程3");
        thread3.start();
    }
}
class MyThread extends Thread {
    public MyThread(String name) {
        super(name);
    }
    @Override
    public void run() {
        System.out.println("继承Thread类执行: " + getName());
    }
}
class MyRunnable implements Runnable {
    private String name;
    public MyRunnable(String name) {
        this.name = name;
    }
    @Override
    public void run() {
        System.out.println("实现Runnable接口执行: " + name);
    }
}

使用线程池 (ExecutorService)

固定线程池

import java.util.concurrent.*;
public class ThreadPoolExample {
    public static void main(String[] args) {
        // 创建固定大小线程池
        ExecutorService executor = Executors.newFixedThreadPool(3);
        // 提交Runnable任务
        for (int i = 0; i < 10; i++) {
            final int taskId = i;
            executor.execute(() -> {
                System.out.println("任务" + taskId + " 由 " + 
                                 Thread.currentThread().getName() + " 执行");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        // 关闭线程池
        executor.shutdown();
    }
}

带返回值的任务 (Callable)

import java.util.concurrent.*;
public class CallableExample {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(3);
        // 提交Callable任务,返回Future
        Future<Integer> future1 = executor.submit(() -> {
            Thread.sleep(2000);
            return 100;
        });
        Future<Integer> future2 = executor.submit(() -> {
            Thread.sleep(1000);
            return 200;
        });
        System.out.println("提交任务完成,等待结果...");
        // 获取结果(会阻塞)
        Integer result1 = future1.get();  // 等待2秒
        Integer result2 = future2.get();  // 等待1秒
        System.out.println("结果1: " + result1 + ", 结果2: " + result2);
        executor.shutdown();
    }
}

完整的生产者-消费者案例

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class ProducerConsumerExample {
    public static void main(String[] args) {
        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(5);
        // 共享队列
        BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(5);
        AtomicInteger taskCounter = new AtomicInteger(0);
        // 提交生产者任务
        executor.submit(new Producer(queue, taskCounter));
        // 提交消费者任务
        for (int i = 0; i < 3; i++) {
            executor.submit(new Consumer(queue, "消费者" + (i + 1)));
        }
        // 运行10秒后关闭
        executor.shutdown();
        try {
            if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
        }
    }
}
class Producer implements Runnable {
    private final BlockingQueue<Integer> queue;
    private final AtomicInteger counter;
    public Producer(BlockingQueue<Integer> queue, AtomicInteger counter) {
        this.queue = queue;
        this.counter = counter;
    }
    @Override
    public void run() {
        try {
            while (!Thread.currentThread().isInterrupted()) {
                int task = counter.incrementAndGet();
                queue.put(task);  // 如果队列满则阻塞
                System.out.println("生产者生产: " + task + 
                                 ", 队列大小: " + queue.size());
                Thread.sleep((long)(Math.random() * 1000));
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
class Consumer implements Runnable {
    private final BlockingQueue<Integer> queue;
    private final String name;
    public Consumer(BlockingQueue<Integer> queue, String name) {
        this.queue = queue;
        this.name = name;
    }
    @Override
    public void run() {
        try {
            while (!Thread.currentThread().isInterrupted()) {
                Integer task = queue.take();  // 如果队列空则阻塞
                System.out.println(name + " 消费: " + task + 
                                 ", 队列大小: " + queue.size());
                Thread.sleep((long)(Math.random() * 2000));
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

使用 CompletableFuture 实现异步编排

import java.util.concurrent.*;
public class CompletableFutureExample {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(3);
        // 异步任务编排
        CompletableFuture<String> future = CompletableFuture
            .supplyAsync(() -> {
                System.out.println("任务1执行: " + Thread.currentThread().getName());
                sleep(1000);
                return "Hello";
            }, executor)
            .thenApplyAsync(result -> {
                System.out.println("任务2执行: " + Thread.currentThread().getName());
                sleep(1000);
                return result + " World";
            }, executor)
            .thenApplyAsync(result -> {
                System.out.println("任务3执行: " + Thread.currentThread().getName());
                sleep(500);
                return result + "!";
            }, executor);
        // 等待结果
        System.out.println("最终结果: " + future.get());  // 输出: Hello World!
        // 多个任务组合
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> 100);
        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> 200);
        CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> 300);
        // 等待所有任务完成
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(future1, future2, future3);
        allFutures.get();  // 阻塞直到所有完成
        // 合并结果
        CompletableFuture<Integer> combinedFuture = 
            future1.thenCombine(future2, (a, b) -> a + b)
                   .thenCombine(future3, (sum, c) -> sum + c);
        System.out.println("总和: " + combinedFuture.get());  // 输出: 600
        executor.shutdown();
    }
    private static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

定时任务执行

import java.util.concurrent.*;
public class ScheduledTaskExample {
    public static void main(String[] args) {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
        // 延迟执行
        scheduler.schedule(() -> {
            System.out.println("延迟3秒执行: " + System.currentTimeMillis());
        }, 3, TimeUnit.SECONDS);
        // 定期执行(固定频率)
        scheduler.scheduleAtFixedRate(() -> {
            System.out.println("每2秒执行一次: " + Thread.currentThread().getName());
        }, 0, 2, TimeUnit.SECONDS);
        // 定期执行(固定延迟)
        scheduler.scheduleWithFixedDelay(() -> {
            System.out.println("任务完成后延迟1秒再执行: " + System.currentTimeMillis());
            try {
                Thread.sleep(500);  // 模拟任务执行时间
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, 1, 1, TimeUnit.SECONDS);
        // 10秒后关闭
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        scheduler.shutdown();
    }
}

提交任务的常用方法对比

方法 返回值 用途 是否阻塞
execute(Runnable) void 提交无返回值的任务
submit(Runnable) Future<?> 提交有返回值的任务
submit(Callable<T>) Future 提交有返回值的任务
invokeAny(Collection<Callable>) T 提交多个任务,返回第一个完成的结果
invokeAll(Collection<Callable>) List<Future> 提交多个任务,等待所有完成

这些案例展示了Java中不同的任务提交和执行方式,从简单的Thread到高级的线程池和CompletableFuture,可以根据具体需求选择合适的实现方式。

抱歉,评论功能暂时关闭!