Java实现多线程的三种方式,以及区别

1.实现多线程的方式有多种:

1.1 继承Thread类
1.2 实现Runnable接口
1.3 实现Callable接口

2.代码实现

2.1 继承java.lang.Thread类
public class ThreadDemo {
    public static void main(String[] args) {
        Thread t1 = new MyThread();
        t1.setName("线程1");
        t1.start();
    }
}

class MyThread extends Thread{
    @Override
    public void run() {
        for (int i = 1; i < 10; i++) {
            System.out.println(Thread.currentThread().getName()+" : "+i);
        }
    }
}
2.2 实现java.lang.Runnable接口
public class RunnableDemo {
    public static void main(String[] args) {
        MyThread02 mt1 = new MyThread02();
        Thread t1 = new Thread(mt1);
        t1.setName("线程1");
        t1.start();
    }
}

class MyThread02 implements Runnable{
    @Override
    public void run() {
        for (int i = 1; i < 10; i++) {
            System.out.println(Thread.currentThread().getName()+" : "+i);
        }
    }
}

2.3 实现java.util.concurrent.Callable接口
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class CallableDemo {
    public static void main(String[] args) throws Exception {
        //创建Callable类型对象
        MyThread03 myThread03 = new MyThread03();
        //将Callable传入FutureTask
        FutureTask<Integer> f1 = new FutureTask<Integer>(myThread03);

        //启动线程
        Thread thread = new Thread(f1);
        thread.setName("线程1");
        thread.start();

        //获取线程返回结果
        Integer integer = f1.get();
        System.out.println(integer);   //1
    }
}

class MyThread03 implements Callable<Integer>{
    @Override
    public Integer call() throws Exception {
        for (int i = 1; i < 10; i++) {
            System.out.println(Thread.currentThread().getName()+" : "+i);
        }
        return 1;
    }
}

3. 三种实现方式的对比

3.1 继承java.lang.Thread类 : 编写简单,由于Java只能单继承,所以该方式不够灵活
3.2 实现java.lang.Runnable接口 :省去了单继承的弊端,编写代码更加灵活
3.3 实现java.util.concurrent.Callable接口 : 有返回值
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值