面试题 --- 2.创建线程的几种方式

一.在Java中,共有四种方式可以创建线程

1.继承Thread类创建线程

public class MyThread extends Thread {
    @Override
    public void run() {
        // 线程将会执行这里的代码
        System.out.println("线程正在运行...");
    }
 
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start(); // 启动线程
    }
}

2.实现Runnable接口创建线程

public class MyRunnable implements Runnable {
    public void run() {
        System.out.println("线程正在运行...");
    }
 
    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
}

3.通过Callable和FutureTask创建线程

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
 
public class CallableAndFuture {
    public static void main(String[] args) {
        // 创建一个实现Callable的任务
        Callable<Integer> task = () -> {
            System.out.println("任务执行中...");
            Thread.sleep(2000); // 模拟耗时操作
            return 123; // 返回结果
        };
 
        // 使用FutureTask来包装Callable任务
        FutureTask<Integer> futureTask = new FutureTask<>(task);
 
        // 创建线程,并执行
        Thread thread = new Thread(futureTask);
        thread.start();
 
        try {
            // 获取任务执行的结果,如果任务还未完成则会阻塞等待
            Integer result = futureTask.get(); // 也可以设置超时时间 futureTask.get(long timeout, TimeUnit unit)
            System.out.println("任务返回的结果:" + result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt(); // 重新设置线程中断状态
        }
    }
}

4.通过线程池创建线程

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

public class ThreadPoolExample {
    public static void main(String[] args) {
        // 创建一个固定大小的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        // 提交任务给线程池执行
        for (int i = 0; i < 5; i++) {
            int taskId = i;
            executorService.submit(() -> {
                // 模拟任务执行时间
                try {
                    Thread.sleep(1000); // 模拟耗时操作
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Task " + taskId + " is running on thread " + Thread.currentThread().getName());
            });
        }

        // 关闭线程池,‌这通常会等待当前已提交的任务执行完毕
        executorService.shutdown();
    }
}

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值