具有Lambda表达式的线程 [英] Thread with Lambda expression

查看:250
本文介绍了具有Lambda表达式的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第42行和第43行出错:主题t1 =新主题(() - > prod.test()); 线程t2 =新线程(() - > cons.test()); 未处理的异常类型InterruptedException 。如果我尝试quickfix它将创建带有catch 异常的try catch,它将具有相同的错误并将尝试以相同的方式修复它,继续用try catch包围它。

I have an error at line 42 and 43 : Thread t1=new Thread(()->prod.test()); , Thread t2=new Thread(()->cons.test()); Unhandled exception type InterruptedException . If I try to quickfix it will created the try catch with an catch Exception, it will have the same error and will try to fix it in the same way continuing to surround it with 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());
    }

}


推荐答案

您已经创建了一个功能接口 Predicate ,其方法被声明为抛出 InterruptedException ,这是一个经过检查的异常。但是,在lambda表达式的主体中调用 test()作为 Thread 构造函数,它接受 Runnable ,其 run()未声明方法抛出任何已检查的异常。因此,由于异常未在正文中捕获,因此会发生编译器错误。

You have created a functional interface Predicate whose method is declared to throw an InterruptedException, which is a checked exception. However, you call test() in the body of a lambda expression as the parameter to the Thread constructor that takes a Runnable, whose run() method is not declared to throw any checked exceptions. Therefore, because the exception is not caught in the body, a compiler error occurs.

顺便说一下,为自己的接口命名可能会造成混淆谓词,因为内置功能界面 java.util.function.Predicate ,其函数方法返回 boolean

Incidentally, it may be confusing to name your own interface Predicate, because of the built-in functional interface java.util.function.Predicate whose functional method returns a boolean.

因为 run()不能抛出异常,你必须 catch 异常并处理它。您可以记录异常及其堆栈跟踪。您可以将异常包装在 RuntimeException 中。无论哪种方式,捕获已检查的异常将允许代码编译。示例:

Because run() can't throw an Exception, you must catch the exception and handle it. You might log the exception and its stack trace. You might wrap the exception in a RuntimeException. Either way, catching the checked exception will allow the code to compile. Example:

Thread t1 = new Thread(() -> {
    try {
        prod.test();
    } catch (InterruptedException e) {
        // handle: log or throw in a wrapped RuntimeException
        throw new RuntimeException("InterruptedException caught in lambda", e);
    }
});

这篇关于具有Lambda表达式的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆