- 继承
Thread
类, 重写run()
方法, 调用start()
方法启动线程.
优点: 在run
方法内获取当前线程直接使用this
就可以了, 无须使用Thread.currentThred()
缺点: ①Java
不支持多继承 ②任务和代码没有分离 ③没有返回值
- 实现
Runnable
接口, 具体实现run()
方法, 也没有返回值.
- 实现
Callable
接口的call()
方法, 使用创建的FutureTask
对象作为任务创建一个线程并启动它, 最后通过futureTask.get()
等待任务执行完毕, 并返回结果.
package com.syq.demo.concurrent.create;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* @Description 三种创建线程的方法
* @Author SYQ
**/
public class CreateThread {
public static void main(String[] args) {
// 继承Thread
Thread t = new MyThread();
t.start();
// 实现Runnable接口
Runnable r = new RunnableTask();
new Thread(r).start();
new Thread(r).start();
// 实现Callable接口, 可以返回值
FutureTask<String> futureTask = new FutureTask<>(new CallerTask());
new Thread(futureTask).start();
try {
// 等待任务执行完毕, 并返回结果
String result = futureTask.get();
System.out.println(result);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public static class MyThread extends Thread {
@Override
public void run() {
System.out.println("thread1 name: " + this.getName());
System.out.println("I am a child thread, extends thread");
}
}
public static class RunnableTask implements Runnable {
@Override
public void run() {
System.out.println("thread2 name: " + Thread.currentThread().getName());
System.out.println("I am a child thread, implements runnable");
}
}
public static class CallerTask implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("thread3 name: " + Thread.currentThread().getName());
return "I am a child thread, implements Callable";
}
}
}