java多线程注意点

多线程执行的程序抛出异常主线程是无法捕获的,要谨慎用,最好用Callable

        ScheduledFuture scheduledFuture = executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {

                synchronized (handlerAndTimer) {

                    System.out.println("定时任务执行");
                    if (counter++ == 5) {
                        throw new RuntimeException("退出当前线程");
                    }

                }
            }
        }, 1, 4, TimeUnit.SECONDS);

Callable

ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        Future submit = executorService.submit(new Callable() {
            @Override
            public Object call() throws Exception {
                return null;
            }
        });
        submit.get(); 
  

                            
                        
                    
                    
                    

你可能感兴趣的:(java多线程注意点)