我在第42和43行有一个错误:Thread t1=new Thread(()->prod.test());,Thread t2=new Thread(()->cons.test()); 未处理的异常类型InterruptedException.如果我尝试quickfix它将创建带有捕获异常的try catch ,它将具有相同的错误,并将尝试以相同的方式修复它,继续用try catch包围它.
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
interface Predicate {
public void test() throws InterruptedException;
}
class MyClass {
int num = 0;
Lock lock = new ReentrantLock();
public void produce() throws InterruptedException {
lock.lock();
for (int i = 0; i < 1000; i++) {
num++;
Thread.sleep(1);
}
lock.unlock();
}
public void consume() throws InterruptedException {
lock.lock();
for (int i = 0; i < 1000; i++) {
num--; …Run Code Online (Sandbox Code Playgroud) 给定一个带有默认方法的简单接口:
private interface A {
default void hello() {
System.out.println("A");
}
}
Run Code Online (Sandbox Code Playgroud)
并且接受它的实例的方法:
private static void print(A a) {
a.hello();
}
Run Code Online (Sandbox Code Playgroud)
我可以使用匿名类覆盖它:
print(new A() {
@Override
public void hello() {
System.out.println("OverHello");
}
});
Run Code Online (Sandbox Code Playgroud)
但如果我尝试使用lambda print(() -> System.out.println("OverHello2"));,我会收到编译错误.
找不到目标方法
有没有办法用lambda进行覆盖?
我想要一个简单的程序,用滑块改变矩形的宽度.当我运行它时,jpanel无法正常工作,因为它只适合panel.width宽度,并且不能正确重新绘制.
import java.awt.*;
import javax.swing.*;
public class panel extends JPanel {
private int width = 50;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GRAY);
g.fillRect(20, 20, width, 25);
}
public void setWidth(int width) {
this.width = (width > 0) ? width : 0;
repaint();
}
public int getWidth() {
return width;
}
}
Run Code Online (Sandbox Code Playgroud)
GUI:
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class Gui extends JFrame {
private panel p;
private JSlider slider;
Gui() {
super("Draw program");
setDefaultCloseOperation(EXIT_ON_CLOSE);
p = new panel(); …Run Code Online (Sandbox Code Playgroud) 在这个例子中
Stream<MyClass>stream = Stream.of(new MyClass(5),new MyClass(15),new MyClass(8),new MyClass(12));
Map<Boolean, List<Integer>> map =
stream.collect(Collectors.partitioningBy(a->a.getNum()<10));
Run Code Online (Sandbox Code Playgroud)
在stream.collect检索地图布尔并List<MyClass>因此它不工作.我应该怎么做才能回到地图Boolean和List<Integer>呢?
我使用a ExecutorService有多个线程将文本写入文件,但我无法设法同步run()方法,而不是正确的逐行字符串我问,我有一个字符串的所有字符的混合,因为他们写它同时.
import java.io.BufferedReader
...
class WriteDns implements Runnable {
File file;
String text;
WriteDns(File file, String text) {
this.file = file;
this.text = text;
}
public void run() {
synchronized (this) {
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file)))) {
bw.write(turnDns() + "\n");
} catch (IOException e) {
System.out.println("Error");
}
}
}
public String turnDns() {
int space = text.indexOf(' ');
String ip = text.substring(0, space);
String theRest = text.substring(space);
String temp = ip; …Run Code Online (Sandbox Code Playgroud)