关于java中的线程池

作者:暴躁小n | 创建时间: 2023-03-22
* Executors 线程池! * 线程池的好处是:线程池里面的线程运行后并不会死亡变成垃圾,而是被线程池回收重复利用! * API:public static ExecutorService newFixedThreadPool(int...
关于java中的线程池

操作方法

首先床架你一个简单的线程实现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); } } }

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

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

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

点击展开全文

更多推荐