线程创建的3种方式和区别

0.区别

继承Thread类实现Runnable接口实现Callable接口
优点:编写简单,如果需要访问当前线程,无需使用**Thread.currentThread()**方法,直接使用this,即可获得当前线程优点:线程类只是实现了Runable接口,还可以继承其他的类。在这种方式下,可以多个线程共享同一个目标对象,所以非常适合多个相同线程来处理同一份资源的情况。优点:可以接收返回值
缺点:继承了Thread类,所以不能再继承其他的父类。缺点:编程稍微复杂,如果需要访问当前线程,必须使用 Thread.currentThread() 方法。\
RunnableCallable
Runnable规定必须重写的方法是run()Callable规定的方法是call()
不能返回值可返回值
run方法不可以抛出异常call方法可以抛出异常
\运行Callable任务可以拿到一个Future对象,通过Future对象可以了解任务执行情况,可取消任务的执行,还可获取执行结果。

1.继承Thread类

输出:继承Thread类,当前线程Name:我是 Thread

public class Main {
    public static void main(String[] args) {
        Thread t1 = new Test();
        t1.setName("我是 Thread");
        t1.start();
    }
}

class Test extends Thread{
    @Override
    public void run() {
        System.out.println("继承Thread类,当前线程Name:"+this.getName());
    }
}

1.5.临时实现Thread类

输出:临时实现Thread类,当前线程Name:我是 临时实现Thread类

public class Main {
    public static void main(String[] args) {
        Test test = new Test();
        Thread t = new Thread("我是 临时实现Thread类"){
            public void run(){
                test.Dog();
            }
        };
        t.start();
    }
}

class Test{
    public void Dog(){
        System.out.println("临时实现Thread类,当前线程Name:"+Thread.currentThread().getName());
    }
}

2.实现Runnable接口

输出:Runnable接口,+线程Name:我是 Runnable

public class Main {
    public static void main(String[] args) {
        TestRun testRun = new TestRun();
        Thread t = new Thread(testRun,"我是 Runnable");
        t.start();
    }
}

class TestRun implements Runnable{

    @Override
    public void run() {
        System.out.println("Runnable接口,+线程Name:"+ Thread.currentThread().getName());
        Dog();
    }

    public String Dog(){
        return "dog";
    }
}

3.实现Callable接口

Callable接口,+线程Name:我是 Callable
Callable 返回值是 dog

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCall testCall = new TestCall();
        FutureTask task = new FutureTask(testCall);
        Thread t = new Thread(task,"我是 Callable");
        t.start();
        System.out.println(task.get());
    }
}

class TestCall implements Callable {

    @Override
    public Object call() throws Exception {
        System.out.println("Callable接口,+线程Name:"+ Thread.currentThread().getName());
        return Dog();
    }

    public String Dog(){
        return "Callable 返回值是 dog";
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值