如何在Servlet Web应用程序中创建Thread?

时间:2016-11-15 14:37:27

标签: java multithreading jsp servlets

我正在使用servlel / jsp创建Web应用程序,并根据我想要创建线程的要求。

下面是我尝试过但没有成功的代码。

我创建了监听器,以便在应用程序启动时调用它。

ThreadListener.java

@WebListener
public class NewsCrawlerThreadListener implements ServletContextListener {

    private ScheduledExecutorService scheduler = null;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        if ((scheduler == null) || (!scheduler.isTerminated())) {
            scheduler = Executors.newSingleThreadScheduledExecutor();
            scheduler.scheduleAtFixedRate(new DemoThread(), 0, 2, TimeUnit.SECONDS);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        try {
            System.out.println("Scheduler Shutting down successfully " + new Date());
            scheduler.shutdown();
        } catch (Exception ex) {
            System.out.println("ERROR IN THREAD ->" + ex.getMessage());
        }
    }
}

演示帖子

public class DemoThread implements Runnable {

    public DemoThread() {

    }

    @Override
    public void run() {
        System.out.println("THREAD START :" + new Date());
        // TODO
        HttpClient httpclient = HttpClients.createDefault();

        try {
            URIBuilder builder = new URIBuilder("https://api.cognitive.microsoft.com/bing/");

            builder.setParameter("mkt", "en-IN");

            URI uri = builder.build();
            HttpGet request = new HttpGet(uri);
            request.setHeader("Ocp-Apim-Subscription-Key", "<api-key>");

            // Request body
            HttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                JSONObject jsonObj = new JSONObject(EntityUtils.toString(entity));

                JSONArray list = jsonObj.getJSONArray("value");
                for (int i = 0; i < list.length(); i++) {
                    JSONObject oj = (JSONObject) list.get(i);
                    System.out.println(oj.get("name"));
                    System.out.println(oj.get("description") + "\n");
                }
            }
            System.out.println("THREAD END :" + new Date());
        } catch (Exception e) {
            System.out.println("Exception in Thread :" + e.getMessage());
        }
    }

}
下面的

是我运行应用程序时的堆栈跟踪

15-Nov-2016 19:22:41.775 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class listener.NewsCrawlerThreadListener
 java.lang.NoClassDefFoundError: org/apache/http/Consts
    at org.apache.http.client.utils.URIBuilder.digestURI(URIBuilder.java:181)
    at org.apache.http.client.utils.URIBuilder.<init>(URIBuilder.java:82)
    at crawling.NewsCrawl.<init>(NewsCrawl.java:33)
    at listener.NewsCrawlerThreadListener.contextInitialized(NewsCrawlerThreadListener.java:30)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4738)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5181)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1780)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: org.apache.http.Consts
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1333)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1167)
    ... 17 more

15-Nov-2016 19:22:55.057 SEVERE [http-nio-8084-exec-10] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class listener.NewsCrawlerThreadListener
 java.lang.NoClassDefFoundError: org/apache/http/Consts
    at org.apache.http.client.utils.URIBuilder.digestURI(URIBuilder.java:181)
    at org.apache.http.client.utils.URIBuilder.<init>(URIBuilder.java:82)
    at crawling.NewsCrawl.<init>(NewsCrawl.java:33)
    at listener.NewsCrawlerThreadListener.contextInitialized(NewsCrawlerThreadListener.java:30)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4738)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5181)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:460)
    at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1586)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
    at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1460)
    at org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:906)
    at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:344)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:614)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: org.apache.http.Consts
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1333)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1167)
    ... 52 more

Web应用程序运行正常,但我创建的线程没有被调用。我不知道我的代码中有什么问题。

任何帮助都将受到高度赞赏

修改

感谢您的回复。

刚刚解决了包括正确版本的jar文件。 将httpcore-4.2.1.jar更改为httpcore-4.4.4.jar并解决问题。

0 个答案:

没有答案