gpt4 book ai didi

java - Servlet线程调度

转载 作者:行者123 更新时间:2023-12-01 18:30:46 24 4
gpt4 key购买 nike

public class Authenticate implements Filter
{
static List<Thread> homethread = new ArrayList<Thread>();
static Queue<Thread> threadQueue = new LinkedList<Thread>();
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException
{
if(homethread.size()>=2)
{
threadQueue.add(Thread.currentThread());
while(!threadQueue.isEmpty())
{
for(Thread th : homethread)
{
if(th.getState()!=Thread.State.TIMED_WAITING)
{
homethread.remove(th);
Thread thr = threadQueue.remove();
homethread.add(thr);
chain.doFilter(request, response);
}
}
}
}
else
{
homethread.add(Thread.currentThread());
chain.doFilter(request, response);
}
}

我已经在过滤器中完成了上述代码,以限制访问 servlet 的用户数量(即登录后出现的主页)

public class Home extends HttpServlet 
{
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter writter = response.getWriter();
writter.println
(
"<!DOCTYPE html>" +
"<html>" +
"<body>" +
"<h1 style=\"text-align:center;\">Provide Your Choice</h1>"+
"<form action=\"Upload\" method=\"POST\">" +//enctype=\"multipart/form-data\"
"<div style=\"text-align:center\">Upload File :<input type=\"file\" name=\"UploadedFile\" multiple/><input type=\"submit\" value=\"Upload\"><br><br>"+
"</form>" +
"<div style=\"text-align:center\">View Files :<input type=\"submit\" formaction=\"View\" formmethod=\"post\" value=\"View\"/><br><br>" +
"<div style=\"text-align:center\"><input type=\"submit\" formaction=\"LogOut\" formmethod=\"post\" value=\"LogOut\"/>" +
"</body>" +
"</html>"
);
response.flushBuffer();
try
{
Thread.currentThread().sleep(50000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}

它显示主页对前 2 位用户的响应良好。我已将后续请求(3,4,5)存储在队列中,并检查之前的主线程(1或2)是否完成其 sleep 状态。如果完成,那么我将删除唤醒线程并弹出第三个线程(即)从队列中取出并让它完成工作(即向第三个用户显示主页并 sleep )。现在,根据我的摩托车,这就是我的预期。

1st User Logs in.

After 10 secs 2nd user Logs in.

After 10 secs 3rd user Logs in and he has to be in wait stage.

After 10 secs 4th user logs in and he has to be in wait stage.

At the time of 50th second 3rd User has to get the response.(i.e)1st User Finished his work.

At the time of 60th second 4th User has to get the response.(i.e)2nd User Finished his work.

But Now the Problem here is both 3rd and 4th user is getting the response at the 50th Second Itself.

任何帮助都会非常有用。提前致谢。

最佳答案

撇开逻辑不谈,您需要使用线程安全集合来存储线程而不是简单的列表。您还可以使用 Semaphore 和预定义的许可数量来限制可以调用过滤器的线程数量,从而获得相同的结果。

关于java - Servlet线程调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60170252/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com