在此之前,你需要先对以下知识有所了解:
相信大家对多线程的概念不是很陌生,当我们需要让JVM虚拟机在后台运行一个方法时,我们常常会用到多线程。
线程池就相当于一个Thread调度系统,能让向线程池中提交的线程进行限制、阻塞和排队处理,让所有线程在你的指引下进行“最大化”的工作。
这里使用Runnable多线程接口进行演示。
打开你的IDE,并新建一个项目或类,将它命名为TestThreadPool
,并将下面的代码替换进去:
1public class TestThreadPool { 2 public static void main(String[] args) { 3 //实例化类 4 TestThreadPool testThreadPool = new TestThreadPool(); 5 //调用动态方法 6 testThreadPool.threadPool(); 7 } 8 9 public void threadPool() { 10 Thread1 thread1 = new Thread1(); 11 Thread thread = new Thread(thread1); 12 thread.run(); 13 } 14} 15 16/** 17 * 线程1 18 */ 19class Thread1 implements Runnable { 20 @Override 21 public void run() { 22 System.out.println("WORKING ON THREAD 1"); 23 } 24}
运行结果:
1WORKING ON THREAD 1
我们不需要将注意力集中到主方法,它只是调用了threadPool
方法。
我们在threadPool
方法中将Thread1
线程进行了实例化和运行。
此次实例我们成功利用Runnable接口调用了Thread实现了多线程。
下章我们会调用本章代码进行基本的线程池应用。
如转载请在文章尾部添加:
原作者来自 adlered 个人技术博客:https://www.stackoverflow.wiki/