Java 中有三种线程创建方式,分别为实现 Runnable 接口的 run 方法,继承 Thread 类 并重写 run 的方法,使用 FutureTask 方式
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* 线程创建与运行
*/
public class Main {
public static void main(String[] args) throws InterruptedException{
//外任务与代码没有分离, 当多个线程执行一样的任务时需要 多份任务代码
MyTread tread = new MyTread(12);
tread.start();
System.out.println(Thread.currentThread().getName());//main
RunableTask runableTask = new RunableTask("21");
//两个线程共用一个 task 代码逻辑
new Thread(runableTask).start();
new Thread(runableTask).start();
//main
//I'm a threadThread-0 12
//I'm a threadThread-1 21
//I'm a threadThread-2 21
//创建异步任务
FutureTask<String> futureTask = new FutureTask<>(new CallerTask());
//启动线程
new Thread(futureTask).start();
try {
//等待任务执行完,返回结果
String s = futureTask.get();
System.out.println(s);//hello
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public static class MyTread extends Thread{
private int age;
public MyTread(int age) {
this.age = age;
}
@Override
public void run() {
//获取当前线程直接使用 this 就可以了
System.out.println("I'm a thread"+this.getName()+" "+age);//I'm a threadThread-0
}
}
public static class RunableTask implements Runnable{
private String age;
public RunableTask(String age) {
this.age = age;
}
@Override
public void run() {
System.out.println("I'm a thread"+Thread.currentThread().getName()+" "+age);
}
}
//创建任务类
public static class CallerTask implements Callable<String>{
@Override
public String call() throws Exception {
return "hello";
}
}
}