跳到主要内容

线程

Runnable 接口 和 Callable 接口​

  • 设计这两个接口都是为了让它们的实例被线程执行。
  • Runnable 是1.0 版本添加的,Callable 是 1.5 版本添加的。
  • Runnable 的 run 方法没有返回值,Callable的 call 方法有返回值。
  • todo 为什么 run 方法是 abstract 的?

Runnable 和 Callable 典型使用场景​

class MyRunnable implements Runnable { 
public void run() {
System.out.println("实现Runnable方式");
}
}
// 使用
new Thread(new MyRunnable()).start();
class MyCallable implements Callable<String> {
public String call() throws Exception {
return "Callable返回值";
}
}
// 使用
FutureTask<String> task = new FutureTask<>(new MyCallable());
new Thread(task).start();
System.out.println(task.get()); // 获取返回值

Thread 类​

Runnable 和线程的关系,就像工作和工人的关系。

Thread 类的 start() 方法会创建新的调用栈(call stack), 而直接调用 Runnable 的 run() 方法会在现有 call stack 中添加 run() 方法。所以多线程运行必须用 Thread 的 start() 方法。

Java 中 Thread 的状态(六种)​

(java 源代码中的注释)

  • NEW - A thread that has not yet started is in this state.
  • RUNNABLE - A thread executing in the Java virtual machine is in this state.
  • BLOCKED - A thread that is blocked waiting for a monitor lock is in this state.
  • WAITING - A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
  • TIMED_WAITING - A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
  • TERMINATED - A thread that has exited is in this state.

(todo exited from where???)

Thread 的状态​

当一个Thread 类实例被新建,但是没有 start() ,是 New 状态。

start() 后,Thread 类实例进入 RUNNABLE 状态。New 状态的 Thread 类实例 start 时,会有一个调用栈被创建。

RUNNABLE 状态的 Thread 类实例被 JVM 选中后,开始运行。

Thread 类实例结束 sleep(), 进入 RUNNABLE 状态

ExecutorService​

使用 ExecutorService 的 execute() 方法也可以执行 Runnable, ExecutorService 会自动管理线程的创建,重复使用和结束,所以当我们不想为每个Runnable各创建一个线程或者不知道应当创建多少线程时,ExecutorService 很有用。

Runnable runnable = new MyRunnable() ;

ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(runnable);
...
executorService.shutDown();

barrier synchronizer​

todo barrier synchronizer