JDK线程池
JDK普通线程池
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class ThreadPoolTests {
private final Logger logger= LoggerFactory.getLogger(ThreadPoolTests.class);
//JDK普通线程池
private ExecutorService executorService= Executors.newFixedThreadPool(5);
private void sleep(long m){
try {
Thread.sleep(m);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void testExecutorService(){
Runnable task=new Runnable() {
@Override
public void run() {
logger.debug("Hello ExecutorService");
}
};
for(int i=0;i<10;i++){
//调用submit方法,线程池会分配一个线程进行执行这个任务
executorService.submit(task);
}
sleep(10000);
}
JDK可执行定时任务线程池
public class ThreadPoolTests {
private final Logger logger= LoggerFactory.getLogger(ThreadPoolTests.class);
//JDK可执行定时任务线程池
private ScheduledExecutorService scheduledExecutorService=Executors.newScheduledThreadPool(5);
private void sleep(long m){
try {
Thread.sleep(m);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void testScheduledExecutorService(){
Runnable task=new Runnable() {
@Override
public void run() {
logger.debug("Hello ScheduledExecutorService");
}
};
//以多少周期进行执行任务
scheduledExecutorService.scheduleAtFixedRate(task,10000,20000, TimeUnit.MILLISECONDS);
sleep(20000);
}
Spring线程池
|