错误的写法
如果按照下图的写法,两个任务不会同时执行,因为是一个线程,两个任务是串行的关系。
可以看到第二个任务是等第一个任务执行完以后,才执行的。
正确的写法
使用线程池,为每一个任务创建一个线程
可以看到两个任务同时执行了,一个任务设定的是1秒后执行,另一个任务设定的是3秒后执行,两个任务同时执行了。
代码
package com.yyy.servlet;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestScheduledExecutorService
*/
@WebServlet("/TestScheduledExecutorService")
public class TestScheduledExecutorService extends HttpServlet {
private static final long serialVersionUID = 1L;
private static long start;
/**
* @see HttpServlet#HttpServlet()
*/
public TestScheduledExecutorService() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
start=System.currentTimeMillis();
//timer比较适用于单个任务
/*Timer timer=new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("执行时间距离开始时间为:"+(System.currentTimeMillis()-start));
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 1000);
timer.schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("执行时间距离开始时间为:"+(System.currentTimeMillis()-start));
}
}, 3000);*/
//要执行多个任务要改成任务调度的线程池
ScheduledExecutorService scheduledExecutorService= Executors.newScheduledThreadPool(2);
scheduledExecutorService.schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("执行时间距离开始时间为:"+(System.currentTimeMillis()-start));
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}, 1000,TimeUnit.MILLISECONDS );
scheduledExecutorService.schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("执行时间距离开始时间为:"+(System.currentTimeMillis()-start));
}}, 3000,TimeUnit.MILLISECONDS );
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}