Java 提供了三种创建线程的方法
- 通过实现Runnable接口
- 通过继承Thread接口
- 通过Callable和Future创建线程
通过实现 Runnable 接口来创建线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| public class RunnableDemo { public static void main(String[] args) { new Thread(new MyThread(),"线程1").start(); new Thread(new Runnable() { @Override public void run() { } },"线程2").start(); } }
class MyThread implements Runnable{
@Override public void run() { } }
|
通过继承Thread类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class ThreadDemo { public static void main(String[] args) { new MyThread().start(); new Thread(new MyThread(), "线程2").start(); } }
class MyThread extends Thread{
@Override public void run() { super.run(); } }
|
通过Callable和Future创建线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| public class FutureDemo { public static void main(String[] args) { MyCallable myCallable = new MyCallable(); FutureTask<String> futureTask = new FutureTask<String>(myCallable); String res = null; try { new Thread(futureTask,"线程1").start(); res = futureTask.get(); } catch (Exception e) { e.printStackTrace(); } System.out.println(res); } }
class MyCallable implements Callable<String>{
@Override public String call() throws Exception { return "success"; } }
|
Runnable 和Callable区别
| 方法名 |
ExecutorService的执行方法 |
ExecutorService.submit()返回值 |
返回的Future调用get()方法 |
线程体 |
|
取消执行 |
| Runnable |
execute和submit |
Future |
null |
run() |
|
不能 |
| Callable |
只能是submit |
Future |
Future定义的泛型T |
call() |
|
Future.cancel能取消执行 |
原文链接:https://blog.csdn.net/u012894692/article/details/80215140