使用固定大小的ThreadPool
java.util.concurrent包提供了很多并发的工具类,下面这段代码是一个简单的线程池的样例代码。
public class FixedThreadPoolDemo { public static void main(String[] args) { // int nThreads=Runtime.getRuntime().availableProcessors(); ExecutorService executorService = Executors.newFixedThreadPool(2); Runnable saveLogTask = new Runnable() { @Override public void run() { try { Thread.currentThread().sleep(2000L); System.out.println("Log is saved by thread" + Thread.currentThread().getId()); } catch (InterruptedException e) { e.printStackTrace(); } } }; Runnable feedBack = new Runnable() { @Override public void run() { try { Thread.currentThread().sleep(2000L); System.out.println("Feedback is called by thread" + Thread.currentThread().getId()); } catch (InterruptedException e) { e.printStackTrace(); } } }; executorService.submit(saveLogTask); System.out.println("Do save log asynchronously."); executorService.submit(feedBack); System.out.println("Call feedback asynchronously."); } }
