JSP使用多线程

noobfresher 2018-04-28 08:59:28
想要开多个线程去访问远程的数据接口(因为需要模拟登陆所以返回较慢,一般需要1-5s),同时在页面上实时显示接口返回数据,想问一下这种怎么做才好?(接口返回数据耗时基本是随机的,所以用callable的话需要等那个较慢的;而用runnable的话怎么在run函数中调用jsp的out或response又是个问题)
刚接触jsp还请各位说得详细点,谢谢~
...全文
847 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
noobfresher 2018-04-28
  • 打赏
  • 举报
回复
贴一下两种方式的实验代码,Runnable的会报IOException Callable: <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page import="java.util.concurrent.*" %> <html> <head> <meta http-equiv="Content-Type" content="text/html"; charset="UTF-8"> <title>Title</title> </head> <%! public class MyCallable implements Callable{ private String url; private String param; public MyCallable(String url, String param){ this.url=url; this.param=param; } public String call() throws Exception{ int ran=(int)(Math.random()*5000); Thread.sleep(ran); return Thread.currentThread().getName()+", "+this.url+", "+this.param+" sleeped "+ran+" milliseconds!"; } } %> <% out.println(String.format("%256s","")); ExecutorService pool = Executors.newFixedThreadPool(5); Callable[] c=new Callable[5]; Future[] f=new Future[5]; for(int i=0;i<5;i++) c[i]=new MyCallable("A"+i,"B"+i); for(int i=0;i<5;i++) f[i]=pool.submit(c[i]); for(int i=0;i<5;i++){ out.println(f[i].get().toString()+"</br>"); out.flush(); } pool.shutdown(); %> Runnable: <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <meta http-equiv="Content-Type" content="text/html"; charset="UTF-8"> <title>Title</title> </head> <%! public static void myFunc(String Bits, javax.servlet.jsp.JspWriter myOut){ try{ myOut.println("<div>"+Bits+"</div>"); } catch(Exception eek) { } } public class MyRunnable implements Runnable{ private String url; private String param; private javax.servlet.jsp.JspWriter myOut; public MyRunnable(String url, String param, javax.servlet.jsp.JspWriter myOut){ this.url=url; this.param=param; this.myOut=myOut; } public void run(){ myFunc(Thread.currentThread().getName()+", "+this.url+", "+this.param, this.myOut); } } %> <% for(int i=0;i<5;i++) new Thread(new MyRunnable("A"+i, "B"+i, out)).start(); %>

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧