子父线程交互

public static void main(String[] args) throws Exception {
    
    

        FutureTask futureTask1 = new FutureTask(new Callable<String>() {
    
    
            @Override
            public String call() throws Exception {
    
    
                Thread.sleep(3000);
                System.out.println(Thread.currentThread().getName() + "---------哈哈哈  1------");
                return Thread.currentThread().getName() + "---------hello  1------";
            }
        });


        FutureTask futureTask2 = new FutureTask(new Callable<String>() {
    
    
            @Override
            public String call() throws Exception {
    
    
                Thread.sleep(3000000);
                System.out.println(Thread.currentThread().getName() + "---------哈哈哈  2------");
//                throw new Exception();
                return "test2";

            }
        });

        new Thread(futureTask1).start();
        new Thread(futureTask2).start();
        System.out.println(futureTask1.get());
        try {
    
    
            futureTask2.get(1,TimeUnit.NANOSECONDS);
        }catch (TimeoutException e) {
    
    
            futureTask2.cancel(true);
            e.printStackTrace();
        }catch (Exception e){
    
    
            System.out.println(e.getMessage());
        }
    }

运行结果

Thread-0---------哈哈哈  1------
Thread-0---------hello  1------
java.util.concurrent.TimeoutException
	at java.util.concurrent.FutureTask.get(FutureTask.java:205)
	at question.ExceptionInChildThread.main(ExceptionInChildThread.java:79)

猜你喜欢

转载自blog.csdn.net/a1773570500/article/details/125877910