线程Run和Start
# 线程的Run与Start
# 概念
- 调用start()方法,程序会启动一个线程,并使这个线程处于就绪状态,当分配到时间片之后便可以执行。
- 调用run()方法,程序会将new Thread(......)的代码视为普通代码,也就是你在一个main方法里面写两个线程任务,然后调用run()方法,那么它们就是顺序执行的。
# 代码
# 调用start()方法
public static void main(String[] args) {
new Thread(() -> {
try {
Thread.sleep(600);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("A");
}).start();
new Thread(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("B");
}).start();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
A线程sleep的时间比B长,所以输出结果是 B A。
# 调用run()方法
public static void main(String[] args) {
new Thread(() -> {
try {
Thread.sleep(1600);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("A");
}).run();
new Thread(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("B");
}).run();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
根据上面说的,直接调用run方法,效果其实就是普通代码块,并没有以多线程的方式执行,所以输出 A B。
编辑 (opens new window)
上次更新: 2023/05/28, 08:23:00