【发布时间】:2017-02-27 20:07:52
【问题描述】:
我有一个接口说VegetableCreation 有一个方法:
public void writeVeggieDataIntoFile();
还有两个不同的类Apple 和Mango 实现VegetableCreation。
还有一个工厂类 VegetableFactory 和 create() 方法:
public class VegetableFactory {
public VegetableCreation create(String arg0) {
if (arg0.equals("Apple"))
return new Apple();
else if (arg0.equals("Mango")
return new Mango();
else {
// create and return both apple and mango by spawning two different threads
// so that the writeVeggieDataIntoFile(); gets invoked concurrently
// for both apple and mango and two different file is created
}
}
}
我在这里基本上想要实现的是,当我从客户端类的main() 方法调用VegetableFactory 类的create() 方法并传递除"Apple" 或"Mango" 以外的任何字符串值作为运行时参数。我希望两个不同的线程在每个 Apple 和 Mango 对象上工作,并在每个 writeVeggieDataIntoFile() 方法上同时工作。
任何关于设计策略/或使用哪些并发 API 等的建议都将受到高度赞赏。
P.S.:我应该叫它水果**而不是蔬菜*
【问题讨论】:
-
这很简单。你有什么策略
-
练习的目标是什么?学习低级线程处理?学习如何使用执行器?学习如何使用并行流?这看起来不像是使用多线程的典型用例,所以选择你想学的东西(或者你的老师想让你学的东西)。
-
@JBNizet 我需要这样做来编写两个不同的相当大的文件。苹果和芒果只是一个例子。如果我按顺序执行此过程太慢了。我在现实生活中几乎没有做过很多线程处理,所以我想在设计它时要非常小心。
-
如果您在方法中所做的只是写入文件,并且两个文件都在同一个磁盘上,那么使其成为多线程可能会使其更慢,而不是更快。但是您可以通过简单地使用并行流或具有两个线程的执行器来测试它。
-
@shashwatZing 如果您需要创建 2 个或更多实例并且它们必须同时运行,则需要使用线程。
标签: java multithreading future runnable callable