Skip to content

Commit a08e9da

Browse files
author
yangfei
committed
update
1 parent dadddb3 commit a08e9da

2 files changed

Lines changed: 95 additions & 0 deletions

File tree

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.yf.java.study.thread.notify;
2+
3+
import org.apache.commons.logging.Log;
4+
import org.apache.commons.logging.LogFactory;
5+
6+
/**
7+
* @Author: YangFei
8+
* @Description: 用来在启动后,等待唤醒
9+
* @create: 2020-02-02 23:34
10+
*/
11+
public class ChildNotifyThread implements Runnable {
12+
13+
/**
14+
* 日志
15+
*/
16+
private static final Log LOGGER = LogFactory.getLog(ChildNotifyThread.class);
17+
18+
@Override
19+
public void run() {
20+
Thread currentThread = Thread.currentThread();
21+
long id = currentThread.getId();
22+
ChildNotifyThread.LOGGER.info("线程" + id + "启动成功,准备进入等待状态");
23+
synchronized (ParentNotifyThread.WAIT_CHILEOBJECT) {
24+
try {
25+
ParentNotifyThread.WAIT_CHILEOBJECT.wait();
26+
} catch (InterruptedException e) {
27+
ChildNotifyThread.LOGGER.error(e.getMessage(), e);
28+
}
29+
}
30+
//执行到这里,说明线程被唤醒了
31+
ChildNotifyThread.LOGGER.info("线程" + id + "被唤醒!");
32+
}
33+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package com.yf.java.study.thread.notify;
2+
3+
import org.apache.log4j.BasicConfigurator;
4+
5+
/**
6+
* @Author: YangFei
7+
* @Description: notify方法测试, 这个线程用来发出notify请求
8+
* @create: 2020-02-02 23:21
9+
*/
10+
public class ParentNotifyThread implements Runnable {
11+
12+
/**
13+
* 这个对象的“钥匙”,为每个ChildNotifyThread对象所持有,
14+
* 模拟这个对象为所有ChildNotifyThread对象都要进行独占的现象
15+
*/
16+
public static final Object WAIT_CHILEOBJECT = new Object();
17+
18+
static {
19+
BasicConfigurator.configure();
20+
}
21+
22+
public static void main(String[] args) {
23+
new Thread(new ParentNotifyThread()).start();
24+
}
25+
26+
@Override
27+
public void run() {
28+
29+
/*
30+
* 3个进行WAIT_CHILEOBJECT对象独立抢占的线程,观察情况
31+
* */
32+
int maxIndex = 3;
33+
for (int index = 0; index < maxIndex; index++) {
34+
ChildNotifyThread childNotify = new ChildNotifyThread();
35+
Thread childNotifyThread = new Thread(childNotify);
36+
childNotifyThread.start();
37+
}
38+
39+
/*
40+
* 请在这里加eclipse断点,
41+
* 以便保证ChildNotifyThread中的wait()方法首先被执行了。
42+
*
43+
* 真实环境下,您可以通过一个布尔型(或者其他方式)进行阻塞判断
44+
* 还可以使用CountDownLatch类
45+
* */
46+
synchronized (ParentNotifyThread.WAIT_CHILEOBJECT) {
47+
// ParentNotifyThread.WAIT_CHILEOBJECT.notify();
48+
ParentNotifyThread.WAIT_CHILEOBJECT.notifyAll();
49+
}
50+
51+
// 没有具体的演示含义;
52+
// 只是为了保证ParentNotifyThread不会退出
53+
synchronized (ParentNotifyThread.class) {
54+
try {
55+
ParentNotifyThread.class.wait();
56+
} catch (InterruptedException e) {
57+
e.printStackTrace();
58+
}
59+
}
60+
}
61+
62+
}

0 commit comments

Comments
 (0)