文章会有【原创】或者【转载】标示,部分来自Google Baidu的学习结果 {Java/PHP/Python/Ruby/Go}

Java 在学习二十四【原创】  


Java 线程池

线程不是越多越好,如果无限制的创建线程,创建、销毁都有很多的消耗;

1Executors.newFixedThreadPool 创建线程池【多个】

2Executors.newSingleThreadExecutor() 创建单个线程

3Executors.newCachedThreadPool

4Executors.newScheduledThreadPool

package Thread;


import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;


import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.Future;


public class Test22 {


public static void main(String[] args) {

// TODO Auto-generated method stub

// ExecutorService threadPool = Executors.newFixedThreadPool(3);

// ExecutorService threadPool = Executors.newSingleThreadExecutor();

ExecutorService threadPool = Executors.newCachedThreadPool();

for (int i = 0; i < 5; i++) {

final int task = i;

threadPool.execute(new Runnable() {

@Override

public void run() {

for (int j = 0; j < 2; j++) {

System.out.println(Thread.currentThread().getName() + "执行第" + task + "个任务的第" + j + "此循环");

}

}

});

}

threadPool.shutdown();

System.out.println("#############################");

ExecutorService threadPool1 = Executors.newFixedThreadPool(3);

for (int j = 0; j < 5; j++) {

Future<String> future = threadPool1.submit(new Callable<String>() {

@Override

public String call() throws Exception {

System.out.println(Thread.currentThread().getName() + "任务开始...");

Thread.sleep(1000);

System.out.println(Thread.currentThread().getName() + "任务结束...");

return "ok";

}

});


String value = null;

try {

value = future.get();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (ExecutionException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}


System.out.println(Thread.currentThread().getName() + ":" + value);

}

}


}



package Thread;


import java.util.concurrent.Executors;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.TimeUnit;


public class Test23 {


public static void main(String[] args) {

// TODO Auto-generated method stub

ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(1);

threadPool.scheduleAtFixedRate(new Runnable() {

@Override

public void run() {

System.out.println("Test.."); 

}

}, 2,10, TimeUnit.SECONDS); //每隔2秒延迟10秒执行

}


}



【注意】以上任务执行时没有返回值 void