开启多线程的三种方式

继承Thread接口

 1package com.atguigu.juc.MyLock;
2
3public class ThreadDemo {
4    public static void main(String[] args) {
5        MyThread myThread = new MyThread();
6        myThread.start();
7    }
8
9}
10
11class MyThread extends Thread {
12
13    @Override
14    public void run() {
15        System.out.println("线程" + Thread.currentThread().getName() + "运行了");
16    }
17}

实现Runable接口

 1package com.atguigu.juc.MyLock;
2
3public class ThreadDemo {
4    public static void main(String[] args) {
5        Thread thread = new Thread(new MyThread());
6        thread.start();
7
8    }
9
10}
11
12class MyThread implements Runnable {
13
14    @Override
15    public void run() {
16        System.out.println("线程" + Thread.currentThread().getName() + "运行了");
17    }
18}

实现Callable接口

 1package com.atguigu.juc.MyLock;
2
3import java.util.concurrent.Callable;
4import java.util.concurrent.ExecutionException;
5import java.util.concurrent.FutureTask;
6
7public class ThreadDemo {
8    public static void main(String[] args) throws ExecutionException, InterruptedException {
9        FutureTask futureTask = new FutureTask(new MyThread());
10        Thread thread = new Thread(futureTask);
11        thread.start();
12        Integer res  =(Integer) futureTask.get();
13        System.out.println("res=" + res);
14
15    }
16
17}
18
19class MyThread implements Callable<Integer{
20
21    @Override
22    public Integer call() throws Exception {
23        System.out.println("线程" + Thread.currentThread().getName() + "运行了");
24        return 1024;
25    }
26}

对比

实现Runable接口的run方法是没有返回值的,而实现Callable接口的call方法有返回值.我们可以根据需要选取不同的方式进行多线程的创建.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值