前言
在此之前,你需要先对以下知识有所了解:
相信大家对多线程的概念不是很陌生,当我们需要让JVM虚拟机在后台运行一个方法时,我们常常会用到多线程。
线程池就相当于一个Thread调度系统,能让向线程池中提交的线程进行限制、阻塞和排队处理,让所有线程在你的指引下进行“最大化”的工作。
创建一个线程实例并运行测试
这里使用Runnable多线程接口进行演示。
打开你的IDE,并新建一个项目或类,将它命名为TestThreadPool
,并将下面的代码替换进去:
public class TestThreadPool {
public static void main(String[] args) {
//实例化类
TestThreadPool testThreadPool = new TestThreadPool();
//调用动态方法
testThreadPool.threadPool();
}
public void threadPool() {
Thread1 thread1 = new Thread1();
Thread thread = new Thread(thread1);
thread.run();
}
}
/**
* 线程1
*/
class Thread1 implements Runnable {
@Override
public void run() {
System.out.println("WORKING ON THREAD 1");
}
}
运行结果:
WORKING ON THREAD 1
我们不需要将注意力集中到主方法,它只是调用了threadPool
方法。
我们在threadPool
方法中将Thread1
线程进行了实例化和运行。
后语
此次实例我们成功利用Runnable接口调用了Thread实现了多线程。
下章我们会调用本章代码进行基本的线程池应用。
点我跳转下章:(贰)简单的线程池应用