The way to create Java threads 4: Use a thread pool


java.util.concurrent.ExecutorService Import;
Import java.util.concurrent.Executors;
Import java.util.concurrent.ThreadPoolExecutor;

/ **
* Create a thread Four ways: using a thread pool
*
* Benefits:
* 1. To improve the response speed (reducing the time to create a new thread)
* 2. reduce consumption of resources (reuse of threads in the thread pool, do not need to create each time)
* 3. facilitate thread management
* corePoolSize: the size of the core pool
* maximumPoolSize: maximum number of threads
* keepAliveTime: after how long to keep up to the task when the thread does not terminate
*
*
* face questions: there are several ways to create multi-threaded? Four kinds!
* /

Class NumberThread the implements the Runnable {

@Override
public void RUN () {
for (int I = 0; I <= 100; I ++) {
IF (I% 2 == 0) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
}

class NumberThread1 implements Runnable{

@Override
public void run() {
for(int i = 0;i <= 100;i++){
if(i % 2 != 0){
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
}

public class ThreadPool {

public static void main(String[] args) {
//1. 提供指定线程数量的线程池
ExecutorService service = Executors.newFixedThreadPool(10);
ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
// Set the thread pool properties
// System.out.println (service.getClass ());
// service1.setCorePoolSize (15);
// service1.setKeepAliveTime ();


. @ 2 operations for performing the specified thread. Runnable interface needs to provide an object that implements the class or interface Callable
service.execute (new NumberThread ()); // for suitable Runnable
service.execute (new new NumberThread1 ()); // for suitable Runnable

// service.submit ( Callable callable); // suitable for use in a Callable
// close the connection pool. 3.
service.shutdown ();
}

}

Guess you like

Origin www.cnblogs.com/wpy188/p/12099906.html