有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

I am trying to run following but I am facing null pointer at userService.getName(); without thread it is working fine but with thread it is throwing null pointer exception

         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) 个答案

  1. # 1 楼答案

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