假设我在Java 8中有以下功能接口:
interface Action<T, U> {
U execute(T t);
}
Run Code Online (Sandbox Code Playgroud)
在某些情况下,我需要一个没有参数或返回类型的操作.所以我写这样的东西:
Action<Void, Void> a = () -> { System.out.println("Do nothing!"); };
Run Code Online (Sandbox Code Playgroud)
但是,它给了我编译错误,我需要把它写成
Action<Void, Void> a = (Void v) -> { System.out.println("Do nothing!"); return null;};
Run Code Online (Sandbox Code Playgroud)
这很难看.有没有办法摆脱Void类型参数?
嘿,我正在写一个网络应用程序,我在其中读取一些自定义二进制格式的数据包.我正在开始一个后台线程来等待传入的数据.问题是,编译器不允许我将任何代码抛出(检查)异常run().它说:
run() in (...).Listener cannot implement run() in java.lang.Runnable; overridden method does not throw java.io.IOException
我希望异常杀死该线程,并让它在父线程的某处被捕获.这是可能实现还是我必须处理线程内的每个异常?
为什么在下面的代码"public void run()throws InterruptedException "创建一个编译错误,但"public void run()抛出RuntimeException "不?
InterruptedException引发的编译错误是"Exception InterruptedException与Runnable.run()中的throws子句不兼容"
是因为RuntimeException是未经检查的异常因此不会更改run()签名吗?
public class MyThread implements Runnable{
String name;
public MyThread(String name){
this.name = name;
}
@Override
public void run() throws RuntimeException{
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(Math.round(100*Math.random()));
System.out.println(i+" "+name);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Thread thread1 = new Thread (new MyThread("Jay"));
Thread thread2 = new Thread (new …Run Code Online (Sandbox Code Playgroud)