创建线程的三种方式-(继承Threads,实现Runnable接口,实现Callable接口)

综述

Java使用Thread类代表线程,所有的线程对象都必须是Thread类或其子类的实例。Java可以用三种方式来创建线程,如下所示:

1)继承Thread类创建线程

2)实现Runnable接口创建线程

3)使用Callable和Future创建线程

下面让我们分别来看看这三种创建线程的方法。

demo实例演示

package com.dlut.jeremy;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {
    public static void main(String[] args) {
        // 这是通过继承Thread类创建的线程
        MyThread1 mt1 = new MyThread1();
        mt1.start();
        // 这是实现Runnable接口,比上述步骤多一步
        MyThread2 mt2 = new MyThread2();
        Thread t2 = new Thread(mt2);
        t2.start();
        // 这是实现callable接口
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        // 启动线程,并且带返回值的
        Future <String> future = threadPool.submit(new CallableTest());

        try {
            System.out.println("waiting thread to finish");
            System.out.println(future.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
class MyThread1 extends Thread {

    @Override
    public void run() {
        System.out.println("Thread Body, extends Thread class");
    }

}
class MyThread2 implements Runnable{

    @Override
    public void run() {
        System.out.println("Thread Body, implement Runnable interface");
    }

}

class CallableTest implements Callable <String>{
    public String call() throws Exception{
        return "Hello World";
    }
}


程序运行结果:

Thread Body, extends Thread class
Thread Body, implement Runnable interface
waiting thread to finish
Hello World
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值