多语言展示
当前在线:1860今日阅读:55今日分享:34

关于java中的线程池

* Executors 线程池! * 线程池的好处是:线程池里面的线程运行后并不会死亡变成垃圾,而是被线程池回收重复利用! * API:public static ExecutorService newFixedThreadPool(int nThreads)
工具/原料

java

方法/步骤
1

首先床架你一个简单的线程实现Runnable重写run();public class MyRunnable implements Runnable{ @Override public void run() { for(int i=0; i<100; i++) { System.out.println(Thread.currentThread().getName() + '---' + i); } }}

2

在main方法中创建线程池:ExecutorService pool = Executors.newFixedThreadPool(2);2代表你要在线程池里创建2个线程

3

调用submit即可:pool.submit(new MyRunnable()); pool.submit(new MyRunnable());

4

截取部分结果:pool-1-thread-1---21pool-1-thread-2---22pool-1-thread-1---22pool-1-thread-2---23pool-1-thread-1---23pool-1-thread-2---24pool-1-thread-1---24pool-1-thread-2---25pool-1-thread-1---25pool-1-thread-2---26pool-1-thread-1---26

推荐信息