提问人:elvis 提问时间:3/21/2023 更新时间:3/21/2023 访问量:44
如果我在 Java 中创建另一个线程,为什么不会抛出异常?
Why the exception is not thrown if I create another thread in Java?
问:
我有一段代码,其中抛出异常。twitter4j 库中的 createStatus 方法抛出 TwitterException,它扩展了 Exception,因此它是一个选中的异常。
private void simulateTwitterStream(
String[] keywords, int minTweetLength, int maxTweetLength, long sleepTimeMs) throws TwitterException {
while (true) {
String formattedTweetAsRawJson = getFormattedTeet(keywords, minTweetLength, maxTweetLength);
Status status = TwitterObjectFactory.createStatus(formattedTweetAsRawJson);
twitterKafkaStatusListener.onStatus(status);
sleep(sleepTimeMs);
}
}
之后,我在另一个线程中实现了while循环,如下所示:
private void simulateTwitterStream(
String[] keywords, int minTweetLength, int maxTweetLength, long sleepTimeMs) {
Executors.newSingleThreadExecutor().submit(() -> {
while (true) {
String formattedTweetAsRawJson = getFormattedTeet(keywords, minTweetLength, maxTweetLength);
Status status = TwitterObjectFactory.createStatus(formattedTweetAsRawJson);
twitterKafkaStatusListener.onStatus(status);
sleep(sleepTimeMs);
}
});
}
但在这种情况下,我不需要在方法签名处使用throws TwitterException。有人可以解释一下为什么我不需要使用 throws TwitterException 吗?
谢谢
答: 暂无答案
评论
simulateTwitterStream
Executor