创建线程三种方式:
1.继承Thread类(java.lang),重写run方法,调用自身的start启动线程
Thread类底层实现Runable接口
2.实现Runable接口(java.lang),重写run方法,new Thread(本实例对象).start()启动线程
3.实现Callable接口(java.util.concurrent——JUC包下),重写call方法
线程可分为用户线程及守护线程
程序必须等待用户线程完成才停止,但是无需等待守护线程。
注意:run方法必须是void,且不能抛出异常
但是call方法可以抛出异常,且可以用返回值
import java.util.concurrent.*;
public class TestCall implements Callable<Boolean> {
@Override
public Boolean call() throws Exception {
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCall c1 = new TestCall();
TestCall c2 = new TestCall();
ExecutorService executorService = Executors.newFixedThreadPool(2);
Future<Boolean> s1 = executorService.submit(c1);
Future<Boolean> s2 = executorService.submit(c2);
Boolean b1 = s1.get();
Boolean b2 = s2.get();
System.out.println(b1);
}
}
网友评论