线程启动后,HttpServletRequest对象将被覆盖

时间:2018-10-31 16:28:18

标签: java multithreading asynchronous servlets threadpool

我正在尝试异步执行方法,在此方法中将httpServletRequest对象作为参数传递。但是一旦线程启动,传递的请求就会被覆盖。

这是示例代码

class sampleServlet extends servlet{
        doPost(req,res){
        method1(req);
    }
}

method1(httpservletrequest){
new Thread(new Runnable() {
        public void run() {
            method2(httpservletrequest)
    }).start();
}

method2(httpSservletRequest){
//The request object here is different from the passed object
}

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以创建一个不同的类,例如ThreadSample实现Runnable接口,并将HttpServletRequest作为该类的成员。当创建ThreadSample类的对象时,将httpServletRequest作为构造函数参数传递,然后在run方法中,在调用method2时使用实例成员httpServletRequest。

代码看起来像:

public class ThreadSample implements Runnable
{

    private final HttpServletRequest httpServletRequest;



    public ThreadSample(final HttpServletRequest httpServletRequest)
    {
        this.httpServletRequest = httpServletRequest;
    }



    public void run()
    {
        method2(this.httpServletRequest);
    }

}

在Servlet类的doPost方法中,您可以像这样使用ThreadSample:

Thread thread = new Thread(new ThreadSample(httpServletRequest));
thread.start();

我希望这可以解决您的问题。