Thread with Lambda expression

前端 未结 3 1191
耶瑟儿~
耶瑟儿~ 2021-01-04 02:39

I have an error at line 42 and 43 : Thread t1=new Thread(()->prod.test()); , Thread t2=new Thread(()->cons.test()); Unhandled exception t

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-04 03:22

    As @rgettman says, the name Predicate is unhappy... Anyways, you could take advantage of default methods in Java:

    interface PredicateButPleaseChangeMyName {
    
        void test() throws InterruptedException;
    
        default void tryTest() {
           try {
              this.test();
           } catch (InterruptedException e) {
              // handle e (log or wrap in a RuntimeException)
           }
        }
    }
    

    Then, in your main method, simply create the threads by calling the default tryTest() method:

    Thread t1 = new Thread(() -> prod.tryTest());
    Thread t2 = new Thread(() -> cons.tryTest());
    

提交回复
热议问题