Skip to content

Commit 1819261

Browse files
author
bl03615
committed
5.(选做)跑一跑课上的各个例子,加深对多线程的理解
1 parent 1b359ba commit 1819261

2 files changed

Lines changed: 70 additions & 0 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package thread.github.pxd;
2+
3+
public class TestDemonThread {
4+
5+
public static void main(String[] args) {
6+
7+
Runnable task = () -> {
8+
9+
try {
10+
Thread.sleep(5000);
11+
} catch (InterruptedException e) {
12+
e.printStackTrace();
13+
}
14+
15+
Thread t = Thread.currentThread();
16+
System.out.println("当前线程:" + t.getName());
17+
18+
};
19+
20+
Thread thread = new Thread(task);
21+
thread.setName("test-thread-1");
22+
23+
//这个地方如果是守护线程,那么进程里所有的线程都是守护线程,则会在进程结束的时候,会清理掉所有线程
24+
//thread.setDaemon(true);
25+
thread.start();
26+
27+
}
28+
29+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package thread.github.pxd;
2+
3+
public class ThreadJoinTest {
4+
5+
public static void main(String[] args) {
6+
7+
Runnable task = () -> {
8+
9+
try {
10+
Thread.sleep(5000);
11+
} catch (InterruptedException e) {
12+
e.printStackTrace();
13+
}
14+
15+
Thread t = Thread.currentThread();
16+
System.out.println("当前线程:" + t.getName());
17+
18+
};
19+
20+
Thread thread1 = new Thread(task);
21+
thread1.setName("test-thread-1");
22+
23+
Thread thread2 = new Thread(() -> {
24+
try {
25+
Thread t = Thread.currentThread();
26+
System.out.println("当前线程:" + t.getName());
27+
28+
thread1.join();
29+
30+
} catch (InterruptedException e) {
31+
e.printStackTrace();
32+
}
33+
34+
});
35+
thread2.setName("test-thread-2");
36+
37+
thread1.start();
38+
thread2.start();
39+
}
40+
41+
}

0 commit comments

Comments
 (0)