Java Web应用程序中的线程 [英] Threads in a Java Web Application

查看:117
本文介绍了Java Web应用程序中的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个线程来侦听新文件,已修改文件或已删除文件的文件路径。我正在使用一个使用Spring 3,Struts 2和Hibernate 3的Web应用程序。如果我运行该项目,它会加载index.jsp,其中包含文本Hello World。

I need to create a thread that listens to a filepath for new, modified or removed files. I am using a web application that uses Spring 3, Struts 2 and Hibernate 3. If I run the project, it loads the index.jsp which contains the text "Hello World".

问题在于,当我创建一个java Thread()时,它会侦听文件路径并将其分配给index.jsp:

The problem is that when I create a java Thread() that listens to the filepath and assign it to index.jsp:

<action name="" method="runThread" class="TestThreadBean">
     <result>index.jsp</result>
</action>

然后Hello World文本不会出现,因为Thread永远不会停止(这是对,它不应该停止)。我需要此Thread在后台运行,而不会干扰Web应用程序的其余部分。我不想仅为此线程创建单独的Web应用程序。另外,每次创建 new 会话实例时,我都不希望创建 new Thread实例应该只是一个Thread实例,无论有多少Session活动。

Then "Hello World" text does not ever appear because the Thread doesn't ever stop (Which is right, it's not supposed to stop). I need this Thread to be running in the background and not interfere with the rest of the web application. I don't want to create a separate web application just for this Thread though. Also, I don't want a new Thread instance to be created each time a new Session instance is created, there should be just one Thread instance no matter how many Session instances there are active.

推荐答案

基本上,人们会建议不要启动你的容器托管应用程序中的自己的线程,如Web应用程序或企业(EJB)应用程序。

Basically, people will suggest not to start your own thread in a container managed application, like a web application or an enterprise (EJB) application.

这是因为在容器环境中应管理包括线程在内的所有资源通过容器。但恕我直言,如果你知道我们自己的线程及其资源的含义,生命周期,比如用事务等包装这个线程,那么我们可以使用标准方式创建一个线程( new Thread( )),但这只是我的意见。

This is because in a container environment all the resources including threads should be managed by container. But IMHO if you know the implications, and the life cycle of our own thread and its resources, like wrapping this thread with a transaction etc, then we can create a thread by using the standard way (new Thread()), but it is just my opinion.

我建议你在做出决定之前先通过'容器管理线程'。你可以参考 commonJ 一次来获取Container的句柄线程池,但由于这不是标准或容器规范中未提及,它可能不适用于所有容器。这适用于:

I would suggest you to go through the 'Container managed threads' once before you make a decision. You can refer commonJ once to get a handle to Container's thread pool, but as this is not a standard or not mentioned in the container specifications, It may not work for all the containers. This will work for:

  • Weblogic
  • Websphere
  • Tomcat, Jboss and may be for others

这篇关于Java Web应用程序中的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆