wait 释放锁

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class ThreadB2 extends Thread {

/**
* 线程 BBB 持有对象锁 this,即当前对象 threadB2
*/
@Override
public void run() {
synchronized (this) {
System.out.println(Thread.currentThread().getName() + " beg "
+ System.currentTimeMillis());
System.out.println("B2 ing");
System.out.println(Thread.currentThread().getName() + " end "
+ System.currentTimeMillis());
}
}
}

class ThreadA2 extends Thread {

private ThreadB2 threadB2;

public ThreadA2(ThreadB2 threadB2) {
this.threadB2 = threadB2;
}

/**
* 线程 AAA 持有对象锁 threadB2
*/

@Override
public void run() {
//B2 被锁住
synchronized (threadB2) {
System.out.println(Thread.currentThread().getName() + " beg "
+ System.currentTimeMillis());
try {
System.out.println("wait之前:" + threadB2.isAlive());
threadB2.wait();
System.out.println("wait之后:" + threadB2.isAlive());
} catch (InterruptedException e) {
e.printStackTrace();
}
// try {
// Thread.sleep(2000);
// } catch (InterruptedException e) {
// }
System.out.println(Thread.currentThread().getName() + " end "
+ System.currentTimeMillis());
}
}
}

class Run2 {

public static void main(String[] args) {
ThreadB2 threadB2 = new ThreadB2();
threadB2.setName("B2");
ThreadA2 threadA2 = new ThreadA2(threadB2);
threadA2.setName("A2");



threadA2.start();
threadB2.start();
}

}
Donate comment here