简体   繁体   English

Java多线程无法正常工作

[英]Java multithreading is not working right

I am using an Executor with 4 threads. 我正在使用带有4个线程的Executor

Executor exec = Executors.newFixedThreadPool(this.numOfThreads);
        Runnable requestHandler = new Runnable() {
            @Override
            public void run() {
                try {
                    getImageForURL(spURL, 0);
                } catch (IOException ex) {
                } catch (Exception ex) {
                }
            }
        };
        exec.execute(requestHandler);

In getImageForURL , I am printing the name of the thread and the output looks like this. getImageForURL ,我正在打印线程的名称,输出看起来像这样。 The output does not look right, or is this how it is suppose to look? 输出看起来不正确,或者这应该是看起来如何?

name=pool-1-thread-1
name=pool-2-thread-1
name=pool-3-thread-1
name=pool-4-thread-1
name=pool-5-thread-1
name=pool-6-thread-1
name=pool-7-thread-1
name=pool-8-thread-1
name=pool-9-thread-1
name=pool-10-thread-1
name=pool-11-thread-1
name=pool-12-thread-1
name=pool-13-thread-1
name=pool-14-thread-1

You are creating a new pool every time (by repeatedly calling newFixedThreadPool ). 您每次都在创建一个新池(通过重复调用newFixedThreadPool )。 You probably want to create the pool just once (when you start your program), and submit multiple requestHandler to it. 您可能只想创建一个池(启动程序时),然后向其提交多个requestHandler

The output should then look something like: 输出应如下所示:

name=pool-1-thread-1
name=pool-1-thread-1
name=pool-1-thread-2
name=pool-1-thread-1
name=pool-1-thread-1
name=pool-1-thread-2

with the thread number going up to 4 if the pool is fully utilized. 如果该池已被充分利用,则线程号最多为4。

You want your loop to surround just the call to exec.execute(requestHandler) , and not the entire block of code that you have there, otherwise you'll be creating a new threadpool every time. 您希望您的循环包含对exec.execute(requestHandler)的调用,而不要包含在那里的整个代码块,否则,您每次都会创建一个新的exec.execute(requestHandler)

If you loop around just the call to exec.execute(requestHandler) , then your output should look something like this (the order of the statements may vary): 如果仅循环调用exec.execute(requestHandler) ,那么您的输出应类似于以下内容(语句的顺序可能有所不同):

pool-1-thread-1
pool-1-thread-4
pool-1-thread-3
pool-1-thread-2
pool-1-thread-3
pool-1-thread-4
pool-1-thread-1
pool-1-thread-4
pool-1-thread-3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM