创建线程的几种方式

1、继承Thread

public class Example extends Thread{
    @Override
    public void run() {
        System.out.println("继承Thread对象创建线程");
    }
    public static void main(String[] args) {
        Thread thread = new Example();
        thread.start();
        System.out.println("main--run");
    }
}

2、实现Runable接口创建线程

public class Example implements Runnable{
    @Override
    public void run() {
        System.out.println("实现Runnable接口创建线程");
    }
    public static void main(String[] args) {
        Thread thread = new Thread(new Example());
        thread.start();
        System.out.println("main--run");
    }
}

3、实现callable接口

public class Example implements Callable {
    @Override
    public String call(){
        System.out.println("实现callable中的call方法实现线程");
        return "callable方式的返回值";
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 带异步线程返回值的创建方式
        FutureTask<String> future = new FutureTask(new Example());
        Thread thread = new Thread(future);
        thread.start();
        // get方法使线程阻塞
        String s = future.get();
        System.out.println(s);
        System.out.println("main--run");
    }
}

4、使用线程池创建对象

  1. Executors类:Executors类是Java提供的线程池工具类,可以使用其提供的静态工厂方法来创建线程池,如newFixedThreadPool()、newCachedThreadPool()等。// IO密集行型
  2. ThreadPoolExecutor类:ThreadPoolExecutor是Java提供的线程池实现类,可以通过创建ThreadPoolExecutor对象来创建自定义的线程池。
  3. ForkJoinPool类:ForkJoinPool是Java提供的专门用于支持分而治之算法的线程池,可以通过创建ForkJoinPool对象来使用。// CPU密集型
  4. ScheduledExecutorService接口:ScheduledExecutorService是Java提供的用于定时执行任务的线程池接口,可以使用其实现类ScheduledThreadPoolExecutor来创建定时任务线程池。
public static void main(String[] args) throws ExecutionException, InterruptedException {
	ExecutorService executorService = Executors.newSingleThreadExecutor();
	Future<String> submit = executorService.submit(() -> {
		System.out.println("附带返回值的submit");
		return "submit";
	});
	executorService.execute(()->{
		System.out.println("无返回值的execute");
	});
	String s = submit.get();
	System.out.println("submit执行后的返回值:"+s);
	// 关闭线程池
	executorService.shutdown();
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值