java bigpipe_BigPipe(FaceBook使用的页面加载技术) JAVA实现代码示例

柴琨
2023-12-01

代码如下:在使用队列方面没有仔细斟酌,随便找一个过来,就用了。

注意一点,就是不要把 PrintWriter 的实例对象拿到多线程里去用,否则会出莫名其妙的异常。

import java.io.IOException;

import java.io.PrintWriter;

import java.util.concurrent.ArrayBlockingQueue;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class BigPipeServlet extends HttpServlet {

private static ExecutorService executor = Executors.newFixedThreadPool(50);

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

final ArrayBlockingQueue q = new ArrayBlockingQueue(6);

for (int i = 0; i < 6; i++) {

final int id = i + 1;

executor.execute(new Runnable() {

public void run() {

try {

Thread.sleep((int) (Math.random() * 10000));

q.put(pagelet("content" + id, "Wohooo" + id));

} catch (InterruptedException e) {

}

}

});

}

response.setContentType("text/html;charset=gb2312");

PrintWriter out = response.getWriter();

out

.println("

"

+ ""

+ "

" + "
Progressive Loading");

content(out, "content1", "content2", "content3", "content4", "content5", "content6");

out.println("

");

for (int i = 0; i < 6; i++) {

try {

out.println(q.take());

out.flush();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

out.println("");

}

private void content(PrintWriter writer, String... contentIds) {

for (String id : contentIds) {

writer.println("

-
");

}

}

private String pagelet(String id, String content) {

return "";

}

}

 类似资料: