java web 不推荐在servelt service中直接创建新线程。在init中也不推荐。

DON'T spawn threads in  servlets . It's explicily forbidden by the  J2EE  standard. There's a reason for that. 

Web applications are not like traditional client/server applications. Web applications do not run continuously. A web application receives a request from the client (browser), processes it, returns the results and that's it. Each request/response process is independent and it's only by doing various tricks that we can make it appear that there's a larger continuous process at work. 

Because web applications can only respond to requests, they cannot asynchronously push data to the client. Not only is there no process running, the network connection back to the client no longer exists once the response has been processed. A whole new connection has to be established for each request/response. 

Servlets don't run in their own threads. Instead, when a request comes in, the appserver removes a thread from a master thread pool and uses it to drive the servlet's service (doGet/doPost) method. Once the service method has returned, the thread is returned to the thread pool. If you make that thread spawn a child thread, the thread now in the thread pool will no longer be just like all the other threads in the thread pool, so any other process that gets assigned that thread will end up with unpredictable results. 

To handle true independent threads, therefore, you can't spawn them in request service methods. However, you can spawn them in the init() method of a servlet (this is no longer recommended). Or you can create a ContextListener and have it spawn threads.  

Because HTTP cannot send unsolicited data to web clients, however, once the thread wants to notify a client, it cannot push out a notification. Instead, the request handlers must interrogate the thread the next time a request is made. For tracking progress of a long-running operation, usually the client web page is set up to automatically refresh itself. Each refresh request polls the web application server, which can then check the thread status.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值