我有一个java servlet,它设置一个会话变量并调用一个启动一个线程类。我的实现是一个跟随
<Icon />
我有一个执行长过程的线程类,如下所示;
@WebServlet("/ExportLogs")
public class ExportLogs extends HttpServlet
{
public void doGet(HttpServletRequest request , HttpServletResponse response) throws ServletException,IOException
{
Integer completePercent = new Integer(10);
request.getSession().setAttribute("CompletionStatus" , completePercent);
LogExportingProcess export = new LogExportingProcess();
export.start();
}
}
现在我想在LogExportingProcess类中更改completePercent值的值。我怎样才能实现它。
答案 0 :(得分:2)
您必须在创建Session
LogExportingProcess
对象
class LogExportingProcess extends Thread
{
private HttpSession session;
public LogExportingProcess(HttpSession session) {
this.session = session;
}
public void run()
{
session.setAttribute("CompletionStatus" , completePercent);
}
}
并在ExportLogs
类
LogExportingProcess export = new LogExportingProcess(request.getSession());
答案 1 :(得分:0)
整数不可变。 AtomicInteger将是一个很好的替代品。
@WebServlet("/ExportLogs")
public class ExportLogs extends HttpServlet
{
public void doGet( final HttpServletRequest request , final HttpServletResponse response ) throws ServletException,IOException
{
final AtomicInteger completePercent = new AtomicInteger(10);
request.getSession().setAttribute("CompletionStatus" , completePercent);
final LogExportingProcess export = new LogExportingProcess( completePercent );
export.start();
}
}
class LogExportingProcess extends Thread
{
final AtomicInteger completePercent;
public LogExportingProcess( final AtomicInteger completePercent )
{
this.completePercent = completePercent;
}
public void run()
{
completePercent.set( 80 ); //80% complete, substitute with real code
}
}
根据Yogesh Badke的建议,这是优先考虑持有对HttpSession对象的引用,因为HttpSession可以在超时时正常进行垃圾收集,而AtomicInteger只通过共享百分比而不是整个会话信息来增加封装。