我想进入春季多线程,我几乎没有问题.
我在ThreadRating类中有runnable方法.现在我不确定使用它的最佳方式.
选项1我发现:
private void updateRating() {
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) { // test
// thread part
Runnable worker = new ThreadRating(path, i, products.get(i), dao, fileHandler);
executor.execute(worker);
}
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
log.error("There was an error when ending threads");
System.exit(1);
}
System.out.println("Finished all threads");
}
Run Code Online (Sandbox Code Playgroud)
这似乎运行良好.在for循环之后,它等待直到线程完成并结束.
我试过第二个选项
private TaskExecutor taskExecutor;
public UpdateBO(TaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
private void updateRating() {
for (int i …Run Code Online (Sandbox Code Playgroud) 我正在创建文件和文件夹树.我正在改写多线程.我看到的唯一弱点是创建文件夹时.现在它一个接一个(深入).在我写下文件之前,我会检查路径是否存在.如果没有,我使用mkdirs来创建所有缺失的东西.
public void checkDir(String relativePath) {
File file = new File(homePath + relativePath);
if (!file.exists()) {
if (file.mkdirs()) {
log.info("Directory: " + homePath + relativePath + " is created!");
} else {
log.error("Failed to create directory: " + homePath + relativePath + " !");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个问题,当我使用两个线程时会发生什么.一个有A/B/C路径,另一个有A/B/D. 假设我只有一个文件夹但不存在B.所以他们都会检查路径是否存在并且想要创建它.因此其中一个可能会失败,因为另一个会更快.那么我该如何管理呢?
也许我过分思考,但从理论上讲,这种情况可能会发生.目前我使用常规Thread,但我想使用spring TaskExecutor.它自己处理关键部分,但这不是共享变量或任何东西,路径是不同的,所以我认为它不会识别它.
谢谢你的建议.
我正在尝试创建简单的Web服务,即从URL读取JSON并将其返回.我关注了spring.io教程.我可能错过了一些有关命名约定的内容?
我使用的JSON没有很好的命名约定.一些值是大写的,一些小写的其他值是混合的.我理解为与restTemplate正确匹配我需要遵循这些名称.
我的对象结构:
public class Page {
private String name; //works
private String about; // works
private String PHONE; //does not work
private String Website; //does not work
//getters and setters
}
Run Code Online (Sandbox Code Playgroud)
如果我将它们改为公开,它们就会开始工作.
public class Page {
private String name; //works
private String about; // works
public String PHONE; //works
public String Website; //works
//getters and setters
}
Run Code Online (Sandbox Code Playgroud)
这是我使用它的代码的一部分
@RequestMapping(value = "/Test")
public Bubble getBubbleInfo(){
RestTemplate restTemplate = new RestTemplate();
Page page= restTemplate.getForObject("myURL", Page.class);
return page;
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么?它看起来使用私有所需的经典lowerUpper约定但如果我改变它将无法与JSON正确匹配.我能以某种方式为春天命名吗?
//spring, this …Run Code Online (Sandbox Code Playgroud)