Java 线程池 demo Executors.newFixedThreadPool

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

public class ThreadPoolDemo {

    public static void main(String[] args) {
        // 创建一个固定大小的线程池,最多同时执行两个任务
        ExecutorService executor = Executors.newFixedThreadPool(2);

        // 提交任务给线程池执行
        executor.submit(new Task("Task 1"));
        executor.submit(new Task("Task 2"));
        executor.submit(new Task("Task 3"));

        // 关闭线程池,不再接受新的任务,但会等待已提交的任务完成执行
        executor.shutdown();
    }

    static class Task implements Runnable {
        private String name;

        public Task(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println(name + " is executing in " + Thread.currentThread().getName());
            // 模拟任务执行耗时
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(name + " completed");
        }
    }
}

你可能感兴趣的:(kotlin,java,开发语言)