栏目:线程与并发 作者:admin 日期:2018-04-15 评论:0 点击: 907 次
有三种建立线程的方法:
实现 Runnable 接口;
实现 Callable 接口;
继承 Thread 类。
实现 Runnable 和 Callable 接口的类只能当做一个可以在线程中运行的任务,不是真正意义上的线程,因此最后还需要通过 Thread 来调用。可以说任务是通过线程驱动从而执行的。
需要实现 run() 方法。
通过 Thread 调用 start() 方法来启动线程。
1 2 3 4 5 6 7 8 9 10 |
public class MyRunnable implements Runnable { public void run() { // ... } } public static void main(String[] args) { MyRunnable instance = new MyRunnable(); Thread thread = new Thread(instance); thread.start(); } |
与 Runnable 相比,Callable 可以有返回值,返回值通过 FutureTask 进行封装。
1 2 3 4 5 6 7 8 9 10 11 12 |
public class MyCallable implements Callable<Integer> { public Integer call() { return 123; } } public static void main(String[] args) throws ExecutionException, InterruptedException { MyCallable mc = new MyCallable(); FutureTask<Integer> ft = new FutureTask<>(mc); Thread thread = new Thread(ft); thread.start(); System.out.println(ft.get()); } |
同样也是需要实现 run() 方法,并且最后也是调用 start() 方法来启动线程。
1 2 3 4 5 6 7 8 9 |
public class MyThread extends Thread { public void run() { // ... } } public static void main(String[] args) { MyThread mt = new MyThread(); mt.start(); } |
实现接口会更好一些,因为:
Java 不支持多重继承,因此继承了 Thread 类就无法继承其它类,但是可以实现多个接口;
类可能只要求可执行就行,继承整个 Thread 类开销会过大。
------====== 本站公告 ======------
金丝燕网,一个严谨的网站!