实现线程的三种方法

实现线程的三种方法

实现线程有三种方法:

1.实现Runnable接口

2.实现Callable

3.继承Thread类

实现 Runnable 和 Callable 接口的类只能当做一个可以在线程中运行的任务,不是真正意义上的线程,因此最后还需要通过 Thread 来调用。可以说任务是通过线程驱动从而执行的。

1.实现Runnable接口

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("注意Runnable接口,没有返回值");
    }
}
class Test1 {
    public static void main(String[] args) {
        MyRunnable instance = new MyRunnable();
        Thread thread = new Thread(instance);
        thread.start();
    }
}

2.实现Callable

class MyCallable implements Callable<String>{
    @Override
    public String call() throws Exception {
        return "注意Callable是泛型类,返回值就是泛型的类型";
    }
}
class Test2 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyCallable mc = new MyCallable();
        FutureTask<String> ft = new FutureTask<>(mc);
        Thread newThread = new Thread(ft);
        newThread.start();
        System.out.println(ft.get());
    }
}

3.继承Thread类

class MyThread extends Thread {
    public void run() {
        System.out.println("直接继承Thread类,重写run方法");
    }
}

class Test3 {
    public static void main(String[] args) {
        MyThread mt = new MyThread();
        mt.start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值