线程创建的方式

本文介绍了Java中通过继承Thread类、实现Runnable接口、Callable接口以及使用线程池创建线程的方式。重点比较了Runnable与Callable在run和call方法上的区别,以及Callable如何配合Future和FutureTask处理异步执行和异常处理。
摘要由CSDN通过智能技术生成

1.通过继承thread类,重新run方法,调用start方法开启线程

public class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("run......");
    }

    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        t1.start();
        t2.start();

    }
}

2.通过实现接口runnable

public class MyRunable implements Runnable {
    public void run() {
        System.out.println("RUNNABLE RUN...");
    }

    public static void main(String[] args) {
        MyRunable r = new MyRunable();
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        t1.start();
        t2.start();
    }
}

3.通过实现接口callable 

public class MyCallable implements Callable<String>{

    public String call() throws Exception {
        System.out.println(Thread.currentThread().getName());
        return "OK";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyCallable c = new MyCallable();
        FutureTask <String> ft = new FutureTask<String>(c);
        Thread t1 = new Thread(ft);
        t1.start();
        String result = ft.get();
        System.out.println(result);
    }
}

4.通过线程池创建线程,也是实现runable

public class MyExecutors implements Runnable {
    public void run() {
        System.out.printf("MyExecutors is run...");
    }

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        threadPool.submit(new MyExecutors());
        //关闭线程池
        threadPool.shutdown();
    }
}

runnable 与callable的区别

1.runnable调用run方法是没有返回值的

2.callable 调用call方法是有返回值的,是个泛型,和Future,FutureTask配合使用可以用来获取异步执行的结果

3.callable接口的call方法允许抛出异常,而runnable接口的run方法的异常只能内部消化,不能继续上抛

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值