Skip to content

Commit 01d9202

Browse files
committed
线程异常增加监听,主线程感知。
1 parent b6b0b80 commit 01d9202

File tree

2 files changed

+38
-18
lines changed

2 files changed

+38
-18
lines changed

src/main/java/com/jeiao/ThreadMain.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,9 @@
2020
public class ThreadMain {
2121

2222
private static Logger logger = LogManager.getLogger();
23+
public static volatile int threadStatus = 0;
2324

24-
public static void main(String[] args) throws InterruptedException {
25+
public static void main(String[] args) throws Exception {
2526

2627

2728
for (int i = 0; i < 300; i++) {
@@ -48,6 +49,10 @@ public static void main(String[] args) throws InterruptedException {
4849
countDownLatch.await();
4950
executorService.shutdown();
5051

52+
if (threadStatus > 0) {
53+
throw new Exception("线程异常,程序异常退出!");
54+
}
55+
5156
logger.info("最后处理完成后的map数量:"+MemoryCache.orderBeanMap.size());
5257

5358
}
Lines changed: 32 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.jeiao.thread;
22

3+
import com.jeiao.ThreadMain;
34
import com.jeiao.bean.OrderBean;
45
import com.jeiao.common.MemoryCache;
56
import com.jeiao.queue.OrderBeanQueue;
@@ -8,6 +9,7 @@
89

910

1011
import java.util.concurrent.CountDownLatch;
12+
import java.util.concurrent.Executors;
1113

1214

1315
/**
@@ -30,31 +32,44 @@ public OrderBeanThread(String threadName, CountDownLatch countDownLatch) {
3032
}
3133

3234
public void run() {
35+
try {
36+
while (!OrderBeanQueue.isEmpty()) {
37+
OrderBean orderBean = OrderBeanQueue.getOrder();
3338

34-
while (!OrderBeanQueue.isEmpty()) {
35-
OrderBean orderBean = OrderBeanQueue.getOrder();
39+
if (orderBean == null) {
40+
continue;
41+
}
3642

37-
if (orderBean == null) {
38-
continue;
39-
}
4043

41-
try {
42-
Thread.sleep(1000);
43-
} catch (InterruptedException e) {
44-
e.printStackTrace();
45-
}
44+
//测试
45+
//int i = 1 / 0;
46+
47+
try {
48+
Thread.sleep(1000);
49+
} catch (InterruptedException e) {
50+
ThreadMain.threadStatus++;
51+
e.printStackTrace();
52+
throw new Exception(e);
53+
}
4654

47-
logger.info(threadName);
48-
logger.info(countDownLatch.getCount());
4955

50-
String orderId = orderBean.getOrderId();
5156

52-
//do something
57+
logger.info(threadName);
58+
logger.info(countDownLatch.getCount());
5359

54-
MemoryCache.orderBeanMap.put(orderId, orderBean);
60+
String orderId = orderBean.getOrderId();
5561

62+
//do something
63+
64+
MemoryCache.orderBeanMap.put(orderId, orderBean);
65+
}
66+
} catch (Exception e) {
67+
ThreadMain.threadStatus++;
68+
throw new RuntimeException("线程处理异常,线程退出");
69+
70+
}finally {
71+
countDownLatch.countDown();
72+
logger.info(countDownLatch.getCount());
5673
}
57-
countDownLatch.countDown();
58-
logger.info(countDownLatch.getCount());
5974
}
6075
}

0 commit comments

Comments
 (0)