设为首页 加入收藏

TOP

Java线程池深入理解(一)
2018-06-04 08:51:10 】 浏览:157
Tags:Java 线程 深入 理解

import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
 
 
public class TestExecutor {
    @Test
    public void testSingleThreadExecutorPool() {
        ExecutorService pool = Executors.newSingleThreadExecutor();
        Thread t1 = new MyThread();
        Thread t2 = new MyThread();
        Thread t3 = new MyThread();
        Thread t4 = new MyThread();
        Thread t5 = new MyThread();
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);
        pool.execute(t5);
        pool.shutdown();
        /*
        pool-1-thread-1正在执行...
        pool-1-thread-1正在执行...
        pool-1-thread-1正在执行...
        pool-1-thread-1正在执行...
        pool-1-thread-1正在执行...
        */
    }
 
    @Test
    public void testFixThreadExecutorPool() {
        //创建一个可重用固定线程数的线程池
        ExecutorService pool = Executors.newFixedThreadPool(2);
 
        //创建实现了Runnable接口对象,Thread对象当然也实现了Runnable接口
        Thread t1 = new MyThread();
        Thread t2 = new MyThread();
        Thread t3 = new MyThread();
        Thread t4 = new MyThread();
        Thread t5 = new MyThread();
 
        //将线程放入池中进行执行
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);
        pool.execute(t5);
 
        //关闭线程池
        pool.shutdown();
        /*
        *pool-1-thread-1正在执行...
        *pool-1-thread-2正在执行...
        *pool-1-thread-1正在执行...
        *pool-1-thread-2正在执行...
        *pool-1-thread-1正在执行...
        */
    }
 
    @Test
    public void testCachedThreadExecutorPool() {
        //创建一个可重用固定线程数的线程池
        ExecutorService pool = Executors.newCachedThreadPool();
 
        //创建实现了Runnable接口对象,Thread对象当然也实现了Runnable接口
        Thread t1 = new MyThread();
        Thread t2 = new MyThread();
        Thread t3 = new MyThread();
        Thread t4 = new MyThread();
        Thread t5 = new MyThread();
 
        //将线程放入池中进行执行
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);
   

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇使用MFC创建C++程序 下一篇使用C++实现图形的旋转、缩放、平..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目