【发布时间】:2015-07-14 20:35:49
【问题描述】:
我在第 42 和 43 行有一个错误:Thread t1=new Thread(()->prod.test());、Thread t2=new Thread(()->cons.test()); 未处理的异常类型 InterruptedException。如果我尝试快速修复,它会创建带有 catch Exception 的 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--;
Thread.sleep(1);
}
lock.unlock();
}
public int getNum() {
return num;
}
}
public class Main00 {
public static void main(String[] args) throws InterruptedException {
MyClass c = new MyClass();
Predicate prod = c::produce;
Predicate cons = c::consume;
Thread t1 = new Thread(() -> prod.test());
Thread t2 = new Thread(() -> cons.test());
long start = System.currentTimeMillis();
t1.start();
t2.start();
t1.join();
t2.join();
long end = System.currentTimeMillis();
System.out.println("time taken " + (end - start) + " num = "
+ c.getNum());
}
}
【问题讨论】:
标签: java multithreading lambda interrupted-exception