您的位置:首页 > 编程语言 > Java开发

Java自带的线程池Executors.newFixedThreadPool

2016-09-27 14:20 597 查看
  线程池的基本思想还是一种对象池的思想,开辟一块内存空间,里面存放了众多(未死亡)的线程,池中线程执行调度由池管理器来处理。当有线程任务时,从池中取一个,执行完成后线程对象归池,这样可以避免反复创建线程对象所带来的性能开销,节省了系统的资源。 

  在Java5之前,要实现一个线程池是相当有难度的,现在Java5为我们做好了一切,我们只需要按照提供的API来使用,即可享受线程池带来的极大便利。 

  Java5的线程池分好多种:具体的可以分为两类,固定尺寸的线程池、可变尺寸连接池。 

  在使用线程池之前,必须知道如何去创建一个线程池,在Java5中,需要了解的是java.util.concurrent.Executors类的API,这个类提供大量创建连接池的静态方法,是必须掌握的。

一、固定大小的线程池,newFixedThreadPool:

class TestThread extends Thread {

private String flag;

public TestThread(String flag) {
this.flag = flag;
}

@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "正在执行。。。" + flag);
}
}

@Test
public void fixedThreadPoolTest() {

// 创建一个可重用固定线程数的线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
// 创建线程
Thread t1 = new TestThread("111");
Thread t2 = new TestThread("222");
Thread t3 = new TestThread("333");
Thread t4 = new TestThread("444");
Thread t5 = new TestThread("555");

// 将线程放入池中进行执行
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);

// 关闭线程池
pool.shutdown();
}
输出结果:
pool-1-thread-1正在执行。。。111
pool-1-thread-3正在执行。。。333
pool-1-thread-2正在执行。。。222
pool-1-thread-4正在执行。。。444
pool-1-thread-5正在执行。。。555
改变ExecutorService pool = Executors.newFixedThreadPool(5)中的参数:ExecutorService pool = Executors.newFixedThreadPool(2),输出结果是:
pool-1-thread-1正在执行。。。111
pool-1-thread-2正在执行。。。222
pool-1-thread-2正在执行。。。333
pool-1-thread-1正在执行。。。444
pool-1-thread-2正在执行。。。555
从以上结果可以看出,newFixedThreadPool的参数指定了可以运行的线程的最大数目,超过这个数目的线程加进去以后,不会立即运行,而是被放入任务队列中等待执行。其次,加入线程池的线程属于托管状态,线程的运行不受加入顺序的影响。

二、单任务线程池,newSingleThreadExecutor:

仅仅是把上述代码中的ExecutorService pool = Executors.newFixedThreadPool(2)改为ExecutorService pool = Executors.newSingleThreadExecutor();

@Test
public void singleThreadPoolTest() {

// 创建一个单任务线程池
ExecutorService pool = Executors.newSingleThreadExecutor();
// 创建线程
Thread t1 = new TestThread("111");
Thread t2 = new TestThread("222");
Thread t3 = new TestThread("333");
Thread t4 = new TestThread("444");
Thread t5 = new TestThread("555");

// 将线程放入池中进行执行
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);

// 关闭线程池
pool.shutdown();
}
输出结果:
pool-1-thread-1正在执行。。。111
pool-1-thread-1正在执行。。。222
pool-1-thread-1正在执行。。。333
pool-1-thread-1正在执行。。。444
pool-1-thread-1正在执行。。。555
可以看出,每次调用execute方法,其实最后都是调用了thread-1的run方法。

也可以这样使用

@Test
public void easyMethod() {

ExecutorService pool = Executors.newFixedThreadPool(2);

pool.execute(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("execute method1");
}
});

pool.execute(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("execute method2");
}
});

pool.shutdown();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐