创建线程的4种方式

1. 继承Thread类创建线程

public class Thread1 extends Thread {
    public void run() {
        System.out.println(Thread.currentThread().getName() + " is running...");
    }
    public static void main(String[] args) {
        Thread1 thread1 = new Thread1();
        thread1.setName("thread-1");
        thread1.start();
    }
}

2. 实现Runnable接口创建线程

public class Thread2 implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " is running...");
    }
    public static void main(String[] args) {
        Thread2 thread2 = new Thread2();
        new Thread(thread2,"thread-2").start();
    }
}

3. 使用Callable和Future创建线程

public class Thread3 implements Callable {
    @Override
    public Object call() throws Exception {
        int i = 0;
        for (; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + "-" + i);
        }
        return i;
    }
    public static void main(String[] args) {
        Thread3 thread3 = new Thread3();
        FutureTask futureTask = new FutureTask(thread3);
        new Thread(futureTask, "callThread").start();
        try {
            System.out.println(futureTask.get()); // 获取返回值
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

4. 使用线程池创建

public class Thread4 {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(15);
        executorService.execute(new Thread5());
        try {
            Future future = executorService.submit(new Thread6());
            String result = (String) future.get(); // 获取返回值
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
    }
}

class Thread5 implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " is running...");
    }
}
class Thread6 implements Callable{
    @Override
    public Object call() throws Exception {
        return "thread-6";
    }
}

第3种,第4种,可以获取返回值。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值