gpt4 book ai didi

java - 在 ExecutorService 的 newFixedThreadPool() 中使用队列?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:18:34 24 4
gpt4 key购买 nike

根据 this explanation given in Javadocs , 它说了以下关于

public static ExecutorService newFixedThreadPool(int nThreads)

Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks. The threads in the pool will exist until it is explicitly shutdown.

他们在谈论哪个队列?如果我不在我的多线程应用程序中使用任何队列,如下所示:

ExecutorService service;
service=Executors.newFixedThreadPool(5);
while(true){
try {
s=ss.accept();
//new Thread(new MultithreadedInvocation(s)).start();
service.submit(new MultithreadedInvocation(s)).get();
} catch (InterruptedException | ExecutionException ex) {
ex.printStackTrace();
}

MultithreadedInvocation.java

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class MultithreadedInvocation implements Runnable{
//initialize in const'r
private final Socket socket;

public MultithreadedInvocation(Socket s) {
this.socket=s;
}

@Override
public void run() {
try {
DataInputStream din=new DataInputStream(socket.getInputStream());
DataOutputStream dout=new DataOutputStream(socket.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int str;
str=din.read();
String name=din.readUTF();
System.out.println("Client Name = "+name);
System.out.println("Actual Client requested for file index "+str+".");
ClientInfo ci = new ClientInfo();
ci.ClientName=name;
ci.ClientFileChoice=str;
String fileName = new FileMapping().lookupFile(str);
File tempFile=new File("C:\\Users\\server-3\\Desktop\\List\\"+fileName);
dout.writeLong(tempFile.length());
dout.flush();
din.close();
dout.close();
socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

在这种情况下,我的第 6 个线程会发生什么情况,它会自动添加到那个未知队列,还是线程池将终止,它不会继续运行??

最佳答案

如果您有 5 个线程,然后决定运行一个最多可调用 30 个线程的循环,这些进程将被放入队列中并等待线程可用。

您的第 6 个线程将等待,直到先前提交的线程完成或被取消。

Previous post.

关于java - 在 ExecutorService 的 newFixedThreadPool() 中使用队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31739044/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com