Concurrent - Executors - newFixedThreadPool(int nThreads)

原创转载请注明出处:http://agilestyle.iteye.com/blog/2343518

使用newFixedThreadPool(int nThreads)方法创建的是有界线程池,也就是线程池中的线程个数可以指定最大数量。

MyThread.java

package org.fool.java.concurrent.executor.fixed;

public class MyThread implements Runnable {

    private String name;

    public MyThread(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " name=" + name + " begin " + System.currentTimeMillis());
        System.out.println(Thread.currentThread().getName() + " name=" + name + " end " + System.currentTimeMillis());
    }
}

FixedThreadPoolTest.java

package org.fool.java.concurrent.executor.fixed;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FixedThreadPoolTest {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        for (int i = 0; i < 10; i++) {
            executorService.execute(new MyThread(String.valueOf(i + 1)));
        }
    }
}

Run


Note:

可以看到,执行10次,但是最多只有3个线程在运行。 
 

newFixedThreadPool(int nThreads, ThreadFactory threadFactory)定制线程工厂

FixedThreadPoolTest2.java

package org.fool.java.concurrent.executor.fixed;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class FixedThreadPoolTest2 {
    public static void main(String[] args) {
        MyThreadFactory myThreadFactory = new MyThreadFactory();

        ExecutorService executorService = Executors.newFixedThreadPool(3, myThreadFactory);

        for (int i = 0; i < 10; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + " invoked...");
                }
            });
        }

    }

    public static class MyThreadFactory implements ThreadFactory {

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("My Own Thread " + (int) (Math.random() * 10 + 1));

            return thread;
        }
    }
}

Run

Note:

可以看到,执行10次,但是最多只有3个线程在运行。 

猜你喜欢

转载自agilestyle.iteye.com/blog/2343518