创建线程的方式

我们常说的方式有以下三种:

继承Thread
实现Runable接口
实现Callable接口(可以获取线程执行之后的返回值)

但实际后两种,更准确的理解是创建了一个可执行的任务,要采用多线程的方式执行,

还需要通过创建Thread对象来执行,比如 new Thread(new Runnable(){}).start();这样的方式来执行。

在实际开发中,我们通常采用线程池的方式来完成Thread的创建,更好管理线程资源。

 

案例:如何正确启动线程

class MyThread extends Thread{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+":running.....");
    }
}

public static void main(String[] args){
        MyThread thread = new MyThread();
        //正确启动线程的方式
        //thread.run();//调用方法并非开启新线程
        thread.start();
}

案例:实现runnable只是创建了一个可执行任务,并不是一个线程

class MyTask implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+":running....");
    }
}

public static void main(String[] args){
        MyTask task = new MyTask();
        //task.start(); //并不能直接以线程的方式来启动
        //它表达的是一个任务,需要启动一个线程来执行
        new Thread(task).start();
    }

案例三:runnable vs callable

class MyTask2 implements Callable<Boolean>{

    @Override
    public Boolean call() throws Exception {
        return null;
    }
}

明确一点:

本质上来说创建线程的方式就是继承Thread,就是线程池,内部也是创建好线程对象来执行任务。

原文地址:https://www.cnblogs.com/MJyc/p/13932007.html