gpt4 book ai didi

java - 线程执行服务

转载 作者:行者123 更新时间:2023-11-29 05:30:02 25 4
gpt4 key购买 nike

我的线程的启动方法有问题,我什么都不懂...

我给你看代码:

public class ThreadAction extends Thread{

@Override
public void run() {
ActionFactory factory = new ActionFactory();
IAction action;
for (int i = 0; i < list.size(); i++) {
action = factory.getIAction(list.get(i));
action.setFile(file);
try {
// Creates a random access file stream to read from, and
// optionally to write to
channel = new RandomAccessFile(file, "r").getChannel();
// We put a lock on the file
lock = channel.tryLock(0, file.length(), true);
// after the file has been locked, we can send it
action.send();
// after the file has been sent, we move it in a temporary
// repository specified in the configuration file
lock.release();
channel.close();
Path location = Paths.get(file.getPath());
Path destination = Paths.get(temp);
Files.move(location, destination);
} catch (IOException e) {
logger.error("message", e);
// e.printStackTrace();
} catch (OverlappingFileLockException e) {
logger.error("message", e);
e.printStackTrace();
} catch (SendException e) {
try {
lock.release();
channel.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
logger.error("message", e1);
// e1.printStackTrace();
}
}
}
}

}

我在这里使用我的线程和 thread.start() 但我想使用 executorService 来限制我的线程数量但是当我尝试使用它时没有任何反应!

void init() {
for (Directory dir : configuration.directoriesList) {
list(dir);
}
}

void list(Directory dir) {
File directory = new File(dir.path);
File[] fList = directory.listFiles();
ExecutorService executor = Executors.newFixedThreadPool(8);
if (fList != null) {
for (File f : fList) {
if (f.isFile()) {
ArrayList<IConfig> configList = getActions(f, "ENTRY_CREATE", getDirectoriesList(f), getMatchList(f, getDirectoriesList(f)));
// implement new thread with the good parameters
threadAction = new ThreadAction();
threadAction.setList(configList);
threadAction.setEvent("ENTRY_CREATE");
threadAction.setFile(f);
threadAction.setTemp(temp + "//" + f.getName());
threadAction.start();
} else if (f.isDirectory()) {
list(new Directory(f.getAbsolutePath(), true));
}
}
}

}

如果您知道为什么什么都没有发生...我认为这是因为我现在不使用启动方法?

最佳答案

提交 threadAction 任务后,您需要使用 executor.shutdown() 关闭 ExecutorService。这是为了确保线程不会继续运行。

您创建了一个大小为 8 的线程池,但您只提交了一个任务。要么将 ExecutorService 更改为 Executors.newSingleThreadExecutor(),要么在循环中将 threadAction 的更多实例提交给 ExecutorService。

关于java - 线程执行服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21435115/

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