- 线程池概述 * 程序启动一个新线程成本是比较高的,因为它涉及到要与操作系统进行交互。而使用线程池可以很好的提高性能,尤其是当程序中要创建大量生存期很短的线程时,更应该考虑使用线程池。线程池里的每一个线程代码结束后,并不会死亡,而是再次回到线程池中成为空闲状态,等待下一个对象来使用
ExecutorService pool = Executors.newFixedThreadPool(2);//创建线程池 pool.submit(new MyRunnable()); //将线程放进池子里并执行 pool.submit(new MyRunnable()); pool.shutdown();
多线程(多线程程序实现的方式3)
public void print3() throws InterruptedException { r.lock(); if(flag != 3) { c3.await(); } System.out.print("hk"); System.out.print("\r\n"); flag = 1; c1.signal(); r.unlock(); public class Demo6_Callable { /** * @param args * @throws ExecutionException * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService pool = Executors.newFixedThreadPool(2);//创建线程池 Future<Integer> f1 = pool.submit(new MyCallable(100)); //将线程放进池子里并执行 Future<Integer> f2 = pool.submit(new MyCallable(50)); System.out.println(f1.get()); System.out.println(f2.get()); pool.shutdown(); //关闭线程池 } } class MyCallable implements Callable<Integer> { private int num; public MyCallable(int num) { this.num = num; } @Override public Integer call() throws Exception { int sum = 0; for(int i = 1; i <= num; i++) { sum += i; } return sum; } }