Java 创建多线程的方式总结

应用场景

并发编程的目的是通过同时执行多个任务来提高程序的性能、响应能力和资源利用率。

创建多线程的方式

1、继承Thread类

public class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " run()方法正在执行...");
    }

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
        System.out.println(Thread.currentThread().getName() + " main() 方法执行结束");
    }
}

2、实现Runnable接口

public class MyRunnable implements Runnable {
    public void run() {
        System.out.println(Thread.currentThread().getName() + " run()方法执行中... ");
    }

    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
        System.out.println(Thread.currentThread().getName() + " main() 方法执行完成");
    }
}

3、实现Callable接口

public class MyCallable implements Callable<Integer> {

    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName() + " call() 方法执行中...");
        return 1;
    }

    public static void main(String[] args) {
        FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyCallable());
        Thread thread = new Thread(futureTask);
        thread.start();
        try{
            Thread.sleep(1000);
            System.out.println("返回结果 " + futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " main() 方法执行完成");
    }
}

4、使用线程池

4.1 单线程池 (Executors.newSingleThreadExecutor)

适用于需要保证任务按顺序执行的场景。

public class SingleThreadExecutorTest {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 5; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + " run()方法执行中... ");
                }
            });
        }
        System.out.println("线程任务开始执行....");
        executorService.shutdown();
    }
}
4.2 固定大小的线程池 (Executors.newFixedThreadPool)

适用于负载较为恒定的场景。

public class FixedThreadPoolExample {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("Thread is running: " + Thread.currentThread().getName());
                }
            });
        }
        executorService.shutdown();
    }
}
4.3 缓存的线程池 (Executors.newCachedThreadPool)

适用于执行大量短期异步任务的场景,可以自动回收空闲线程。

public class CachedThreadPoolExample {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("Thread is running: " + Thread.currentThread().getName());
                }
            });
        }
        executorService.shutdown();
    }
}
4.4 调度线程池 (newScheduledThreadPool)

创建一个可以延迟或定期执行任务的线程池。

public class ScheduledThreadPoolExample {
    public static void main(String[] args) {
        // 创建一个具有5个线程的调度线程池
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
        // 安排一个定期执行的任务
        //1:表示初始延迟时间,即任务第一次执行前的等待时间为1秒。
        //3:表示后续执行的间隔时间,即任务第一次执行后,每隔3秒执行一次。
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("Scheduled task is running: " + Thread.currentThread().getName());
            }
        }, 1, 3, TimeUnit.SECONDS);
    }
}
4.5 自定义ThreadPoolExecutor
public class CustomThreadPoolExecutorExample {
    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2,
                4,
                60,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>()
        );

        for (int i = 0; i < 10; i++) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("Thread is running: " + Thread.currentThread().getName());
                }
            });
        }
        executor.shutdown();
    }
}
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值