我们常说的方式有以下三种:
继承Thread
实现Runable接口
实现Callable接口(可以获取线程执行之后的返回值)
但实际后两种,更准确的理解是创建了一个可执行的任务,要采用多线程的方式执行,
还需要通过创建Thread对象来执行,比如 new Thread(new Runnable(){}).start();这样的方式来执行。
在实际开发中,我们通常采用线程池的方式来完成Thread的创建,更好管理线程资源。
案例:如何正确启动线程
1 2 3 4 5 6 7 8 9 10 11 12 13
| 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.start(); }
|
案例:实现runnable只是创建了一个可执行任务,并不是一个线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 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(); new Thread(task).start(); }
|
案例三:runnable vs callable
1 2 3 4 5 6 7
| class MyTask2 implements Callable<Boolean>{
@Override public Boolean call() throws Exception { return null; } }
|
明确一点:
本质上来说创建线程的方式就是继承Thread,就是线程池,内部也是创建好线程对象来执行任务。