线程基础-01
2019-08-16 本文已影响0人
愤怒的奶牛
- 创建线程的三种方式:
- 继承 Thread (本身也是 实现了 Runable 接口)
static class MyThread extends Thread {
@Override
public void run() {
System.out.println("继承 Thread 创建线程");
}
}
- 实现 Runable 接口
static class MyThreadImpl implements Runnable {
@Override
public void run() {
System.out.println("实现 Runnable 接口");
}
}
- 带有返回值的 实现 Callable 接口 (并发包下的接口)
static class MyCallable implements Callable{
@Override
public Object call() throws Exception {
return null;
}
}
- 线程启动
public static void main(String[] args) throws ExecutionException, InterruptedException {
//第一种启动
new MyThread().start();
// 第二种启动
new Thread(new MyThreadImpl()).start();
// 第三种启动,Executors 创建单个线程
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future submit = executorService.submit(new MyCallable());
Object result = submit.get(); //阻塞当前线程(Main),等待MyCallable 线程返回结果。
}