线程

线程的状态

new

就绪

阻塞

运行

结束

start 和 run 的区别

  • Thread.start() 启动新的线程,线程处于就绪(可运行)状态,线程获取到 CPU 资源之后,就执行该线程相应的 run 方法。同一个线程的 start 方法不能被重复调用。
  • Thread.run() 方法内容是线程体,线程具体的执行步骤。run 只是一个方法调用,可以被重复多次调用,不会开辟新的线程。

创建线程的三种方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class HowToCreateThread {
static class MyThread extends Thread {
@Override
public void run() {
System.out.println("extend Thread class to create thread");
}
}

static class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("implement Runnable interface to create thread");
}
}

static class MyCall implements Callable<String> {
@Override
public String call() {
System.out.println("implement Callable interface to create thread");
return "success";
}
}

public static void main(String[] args) {
new MyThread().start();

new Thread(new MyRunnable()).start();

new Thread(() -> System.out.println("implement Runnable interface to create thread")).start();

new Thread(new FutureTask<>(new MyCall())).start();

ExecutorService service = new ThreadPoolExecutor(10, 10, 1000, TimeUnit.MILLISECONDS, new SynchronousQueue<>());
service.execute(() -> System.out.println("implement Runnable interface to create thread"));
service.shutdown();
}
}