Java 提供了三种创建线程的方法

  1. 通过实现Runnable接口
  2. 通过继承Thread接口
  3. 通过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() {
// TODO Auto-generated method stub
}
},"线程2").start();
}
}

/**
* 实现 Runnable 接口的线程类
*/
class MyThread implements Runnable{
/**
* 重写run方法
*/
@Override
public void run() {
// TODO Auto-generated method stub
}
}

通过继承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{
/**
* 重写run方法
*/
@Override
public void run() {
// TODO Auto-generated method stub
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) {
//创建 Callable 实现类的实例
MyCallable myCallable = new MyCallable();
//使用 FutureTask 类来包装 Callable 对象,该 FutureTask 对象封装了该 Callable 对象的 call() 方法的返回值
FutureTask<String> futureTask = new FutureTask<String>(myCallable);
String res = null;
try {
//使用 FutureTask 对象作为 Thread 对象的 target 创建并启动新线程
//没这句,下句代码获取不到结果,会一直等待执行结果
new Thread(futureTask,"线程1").start();
//调用 FutureTask 对象的 get() 方法来获得子线程执行结束后的返回值
res = futureTask.get();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(res);
}
}
/**
* 创建 Callable 接口的实现类,并实现 call() 方法
*/
class MyCallable implements Callable<String>{
/**
* 该call()方法将作为线程执行体,并且有返回值
*/
@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