1. 使用LockSupportpark()unpark() 方法
  2. 使用wait()notify()方法

使用LockSupportpark()unpark() 方法

代码如下:

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
public class LockSupportTest {
static Thread t1 = null;
static Thread t2 = null;

public static void main(String[] args) {
char[] a1 = "1234567".toCharArray();
char[] a2 = "ABCDEFG".toCharArray();

t1 = new Thread(() -> {
for (char c : a1) {
System.out.println(c);
// 叫醒t2
LockSupport.unpark(t2);
// t1阻塞,当前线程阻塞
LockSupport.park();
}
});

t2 = new Thread(() -> {
for (char c : a2) {
// t2阻塞
LockSupport.park();
System.out.println(c);
// 叫醒t1
LockSupport.unpark(t1);


}
});
t1.start();
t2.start();
}
}

使用wait()notify()方法

代码如下:

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
38
39
40
41
42
43
public class WaitNotifyTest {

public static void main(String[] args) {
final Object o = new Object();

char[] a1 = "1234567".toCharArray();
char[] a2 = "ABCDEFG".toCharArray();

new Thread(() -> {
synchronized (o) {
for (char c : a1) {
System.out.println(c);
try {
o.notify();
// 让出锁
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 必须唤醒,不然程序无法终止
o.notify();
}
}, "t1").start();

new Thread(() -> {
synchronized (o) {
for (char c : a2) {
System.out.println(c);
try {
o.notify();
// 让出锁
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 必须唤醒,不然程序无法终止
o.notify();
}
}, "t2").start();
}
}

结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1
A
2
B
3
C
4
D
5
E
6
F
7
G

Process finished with exit code 0

评论