执行异常:从Callable调用方法时

时间:2017-10-02 09:15:31

标签: java scheduler

  
    

我正在尝试运行以下但我在userService.getName()时遇到空指针;     没有线程它工作正常,但有线程它抛出空指针异常

  
         public class Sheduler implements Callable{
            private UserService userService;
            private SchedulerExecuterService scheduler=Executers.newScheduledThreadpool(2);
            @Inject
            public Sheduler (UserService userService){
             this.userService = userService;
             }

            Future future = scheduler.submit(new Callable(){
            @override
            public String call() throws Exception{
            **return userService.getName();//NUll pointer Exception**
            }
            )}

            public void startpool(){
            final Runnable beeper = new Runnable(){
            public void run(){
             UserService userService = new UserService();
             Sheduler  scd=new Sheduler (UserService userService);

            future.get();
            }
            }


            scheduleAtFixedRate(beeper,5,5,TimeUnit.SECONDS);
}

public static void main(){
 Sheduler  scduler=new Sheduler();
   scduler.startpool();
}

1 个答案:

答案 0 :(得分:0)

您在@Inject构造函数上使用Scheduler但仍然手动实例化它。您的UserService从未被注入,因此抛出NullPointerException为空。