副问题[/!--empirenews.page--]
01.无穷制线程的弱点
多线程的软件计划要领确实可以最大限度地施展多核处理赏罚器的计较手段,提跨越产体系的吞吐量和机能。可是,若不加节制和打点的随意行使线程,对体系的机能反而会发生倒霉的影响。
一种最为简朴的线程建设和接纳的要领相同如下:
- new Thread(new Runnable() {
- @Override
- public void run() {
- //do sth
- }
- }).start();
以上代码建设了一条线程,并在run()要领竣事后,自动接纳该线程。在简朴的应用体系中,这段代码并没有太多题目。可是在真实的出产情形中,体系因为真真相形的必要,也许会开启许多线程来支撑其应用。而当线程数目过大时,反而会耗尽CPU和内存资源。
起首,固然与历程对比,线程是一种轻量级的器材,但其建设和封锁依然必要耗费时刻,假如为每一个小的使命都建设一个线程,很有也许呈现建设和烧毁线程所占用的时刻大于该线程真实事变所耗损的时刻,反而会得不偿失。
其次,线程自己也是要占用内存空间的,大量的线程会抢占名贵的内部资源。
因此,在现实出产情形中,线程的数目必需获得节制。盲目地大量建设线程对体系机能是有危险的。
02.简朴的线程池实现
下面给出一个最简朴的线程池,该线程池不是一个完美的线程池,但已经实现了一个根基线程池的焦点成果,有助于快速领略线程池的实现。
1.线程池的实现
- public class ThreadPool {
- private static ThreadPool instance = null;
-
- //空闲的线程行列
- private List<PThread> idleThreads;
- //已有的线程总数
- private int threadCounter;
- private boolean isShutDown = false;
-
- private ThreadPool() {
- this.idleThreads = new Vector<>(5);
- threadCounter = 0;
- }
-
- public int getCreatedThreadCounter() {
- return threadCounter;
- }
-
- //取得线程池的实例
- public synchronized static ThreadPool getInstance() {
- if (instance == null) {
- instance = new ThreadPool();
- }
- return instance;
- }
-
- //将线程池放入池中
- protected synchronized void repool(PThread repoolingThread) {
- if (!isShutDown) {
- idleThreads.add(repoolingThread);
- } else {
- repoolingThread.shutDown();
- }
- }
-
- //遏制池中全部线程
- public synchronized void shutDown() {
- isShutDown = true;
- for (int threadIndex = 0; threadIndex < idleThreads.size(); threadIndex++) {
- PThread pThread = idleThreads.get(threadIndex);
- pThread.shutDown();
- }
- }
-
- //执利用命
- public synchronized void start(Runnable target) {
- PThread thread = null;
- //假若有空闲线程,则直接行使
- if (idleThreads.size() > 0) {
- int lastIndex = idleThreads.size() - 1;
- thread = idleThreads.get(lastIndex);
- idleThreads.remove(thread);
- //当即执行这个使命
- thread.setTarget(target);
- }//没有空闲线程,则建设线程
- else {
- threadCounter++;
- //建设新线程
- thread = new PThread(target, "PThread #" + threadCounter, this);
- //启动这个线程
- thread.start();
- }
- }
-
- }
(编辑:河北网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|