2.继承 hread 重写 run 方法
public static class RunableTask implements Runnable{
@Override
public void run() {
System.out.println (“I am a child thread” );
}
public static void main(String[] args) throws terruptedException{
RunableTask task =new RunableTask();
new Thread(task).start();
new Thread(task).start();
}
}
3.使用futureTask方式
//创建任务类,类似runable
public stat class CallerTask implements Callable{
@Override
public String call () throws Except on {
return "hello ”;
}
public static void main(String[] args) throws InterruptedException {
// 创建异步任务
FutureTask futureTask =new FutureTask<>(new CallerTask()) ;
//启动线程
new Thread(futureTask). start () ;
try {
//等待任务执行完毕,并返回结果
String result = futureTask.get ();
System out printl口( result );
}
catch (ExecutionExcept on e) {
e.printStackTrace() ;
}
}
小结:使用继承方式的好处是方便传参,你可以在子类里面添加成员变量 ,通过 set 方法设置参数或者通过构造函数进行传递,而如果使用 Runnable 方式,则只能使用主线程里面被声明为 final 变量。不好的地方是 Java 支持多继承,如果继承了 Thread 类, 那么子 不能再继