使processRequest等待另一个线程结束

时间:2013-05-08 09:35:08

标签: multithreading jsp servlets wait

我正在为以下代码寻找更好的解决方案, 我有一个必须在用户按下一个按钮时处理请求的servlet, 在做任何事之前,我希望我的函数等待另一个线程结束他正在做的事情, 现在我正在使用一个简单的会话来做这件事:

boolean converted = (Boolean) request.getSession().getAttribute("converterthread");
        while(!converted){ // Wait
            converted = (Boolean) request.getSession().getAttribute("converterthread");
            }

当线程结束他的工作时,它会将会话的converterthread属性设置为true。 这一切都很好,但我担心这不是最好的解决方案,是否每次都要求会话服务器的性能不好? 我正在尝试使用this.wait(1000)来使我的函数检查线程是否每秒都结束,但我只是得到一个监视器未找到异常(或类似)。

编辑:在一个不同的请求方法(在上面的方法之前称为方式)我正在创建一个使用xuggler类进行转换的线程(这样用户不会等待所有的转换都是结束)。 基本上我创建一个新的MyThread(Runnable的扩展),然后我将会话的“converterthread”属性设置为false

MyThread r = new MyThread(uploadedFile, fileDir, request.getSession());
request.getSession().setAttribute("converterthread", false);

过了一会儿,我用MyThread创建了一个线程,然后启动它。 这就是MyThread的样子:

   public class MyThread implements Runnable {

        File uploadedFile;
        File fileDir;
        HttpSession session;
        boolean hasEnded = false;

        public MyThread(File f, File d, HttpSession s) {
            fileDir = d;
            uploadedFile = f;
            session = s;
        }

        public File returnFileDir()
        {
            return fileDir;
        }

        @Override
        public void run() {
            new Converter(uploadedFile.getAbsolutePath(), fileDir.getPath() + "\\video").run();
            //subito dopo voglio eliminare il file precedente
            uploadedFile.delete();  // è sicuro che termina per ultima la conversione
            //Aggiorno lo stato della sessione, sblocca il CutSave se aspettava la conversione
            session.setAttribute("converterthread", true);
            hasEnded = true;
            MyThreadQueue.get().removeThread(this);
            MyThreadQueue.get().runNextThread(); // se c'è un altro thread in attesa allora lo esegue
            //Il meccanismo garantisce un esecuzione dei thread in fila
        }
    }

如您所见,转换后我调用session.setAttribute(“converterthread”,true);

2 个答案:

答案 0 :(得分:0)

您可以使用CountDownLatch,首先在会话中放入countDownLatch

session.setAttribute("latch",new CountDownLatch(1));

工作完成后,请致电

CountDownLatch latch=(CountDownLatch)session.getAttribute("latch");
latch.countDown();

然后将while循环替换为:

CountDownLatch latch=(CoundDownLatch)session.getAttribute("latch");
latch.await(); // will wait for MyThread to call latch.countDown()
//also you can specify a timeout
//latch.await(2000) wait for 2 seconds

更新

最好不要将会话传递到另一个线程,而是可以直接将countDownLatch传递给MyThread实例

答案 1 :(得分:0)

1)您不应该让servlet等待并依赖于正忙于执行其他操作的线程。那不对。

2)如果你真的想要分解你的多个任务,那么有一个简单的方法如下:

>> 在您的jsp / html页面中,创建2 frames

>> 在其中一个框架中,保留用户按下的按钮,该按钮调用servlet。在第二帧中,保留视频处理servlet或任何你想要的。

>> 当用户按下按钮时,该按钮将通过javascript/ajax调用servlet。因此,一旦servlet完成其请求,它就会将响应发送回帧并将响应附加到帧。在第二帧中,更新将以相同的方式发生。