有没有什么办法可以获得当前JVM中所有正在运行的Thread的列表(包括我的类未启动的Threads)?
是否也可以在列表中获取所有Thread的Thread和Class对象?
我希望能够通过代码完成此操作.
我在尝试Java 8的Lambda表达式时遇到了问题.通常它工作正常,但现在我有方法可以抛出IOException.最好看一下以下代码:
class Bank{
....
public Set<String> getActiveAccountNumbers() throws IOException {
Stream<Account> s = accounts.values().stream();
s = s.filter(a -> a.isActive());
Stream<String> ss = s.map(a -> a.getNumber());
return ss.collect(Collectors.toSet());
}
....
}
interface Account{
....
boolean isActive() throws IOException;
String getNumber() throws IOException;
....
}
Run Code Online (Sandbox Code Playgroud)
问题是,它不能编译,因为我必须捕获isActive-和getNumber-Methods的可能例外.但即使我明确使用如下所示的try-catch-Block,它仍然无法编译,因为我没有捕获异常.所以要么JDK中存在错误,要么我不知道如何捕获这些异常.
class Bank{
....
//Doesn't compile either
public Set<String> getActiveAccountNumbers() throws IOException {
try{
Stream<Account> s = accounts.values().stream();
s = s.filter(a -> a.isActive());
Stream<String> ss = s.map(a -> a.getNumber());
return ss.collect(Collectors.toSet());
}catch(IOException ex){
} …Run Code Online (Sandbox Code Playgroud) 关于Java的InterruptedException有一些有趣的问题和答案,例如Java中的InterruptedException和处理InterruptedException 的原因.但是,它们都没有告诉我InterruptedException的可能来源.
那些OS信号如SIGTERM,SIGQUIT,SIGINT?在命令行上按CTRL-C会产生InterruptedException吗?还有什么?
如果我编写如下代码,我们不能中断或终止线程。它也不会抛出 InterruptedException。
Thread loop = new Thread(
new Runnable() {
@Override
public void run() {
while (true) {
}
}
}
);
loop.start();
loop.interrupt();
Run Code Online (Sandbox Code Playgroud)
要中断这个线程,我需要修改我的代码如下:
Thread loop = new Thread(
new Runnable() {
@Override
public void run() {
while (true) {
if (Thread.interrupted()) {
break;
}
// Continue to do nothing
}
}
}
);
loop.start();
loop.interrupt();
Run Code Online (Sandbox Code Playgroud)
我的问题是,
为什么 Java 的设计方式是只有在像 sleep() 和 wait() 这样的阻塞方法的情况下才会抛出InterruptedException。
为什么在普通代码中,我们需要像上面的代码片段那样手动处理?为什么每当我们通过interrupt()方法将中断标志设置为 true 时,Java 不会抛出 InterruptedException ?
我已经阅读了很多关于 InterruptedException 的博客和文章,但没有找到任何令人信服的答案。
编辑
找到关于 …