面试官:公司项目中Java的多线程一般用在哪些场景?
共 7137字,需浏览 15分钟
·
2021-03-06 00:02
阅读本文大概需要 4 分钟。
来自:cnblogs.com/kenshinobiy/p/4671314.html
举个简单的例子:
读取文件1 (10ms) 处理1的数据(1ms) 读取文件2 (10ms) 处理2的数据(1ms) 读取文件3 (10ms) 处理3的数据(1ms) 整合1、2、3的数据结果 (1ms)
读取文件1 (1ms) 处理1的数据(1ms) 读取文件2 (1ms) 处理2的数据(1ms) 读取文件3 (28ms) 处理3的数据(1ms) 整合1、2、3的数据结果 (1ms)
伪代码:
public class MyServlet extends Servlet{
private static Map<String, String> fileName2Data = new HashMap<String, String>();
private void processFile3(String fName){
String data = fileName2Data.get(fName);
if(data==null){
data = readFromFile(fName); //耗时28ms
fileName2Data.put(fName, data);
}
//process with data
}
}
public class MyServlet extends Servlet{
private static ConcurrentHashMap<String, String> fileName2Data = new ConcurrentHashMap<String, String>();
private void processFile3(String fName){
String data = fileName2Data.get(fName);
if(data==null){
data = readFromFile(fName); //耗时28ms
fileName2Data.put(fName, data);
}
//process with data
}
}
public class MyServlet extends Servlet{
private static ConcurrentHashMap<String, String> fileName2Data = new ConcurrentHashMap<String, String>();
private void processFile3(String fName){
String data = fileName2Data.get(fName);
//“偶然”-- 1000个线程同时到这里,同时发现data为null
if(data==null){
data = readFromFile(fName); //耗时28ms
fileName2Data.put(fName, data);
}
//process with data
}
}
public class MyServlet extends Servlet{
private static ConcurrentHashMap<String, FutureTask> fileName2Data = new ConcurrentHashMap<String, FutureTask>();
private static ExecutorService exec = Executors.newCacheThreadPool();
private void processFile3(String fName){
FutureTask data = fileName2Data.get(fName);
//“偶然”-- 1000个线程同时到这里,同时发现data为null
if(data==null){
data = newFutureTask(fName);
FutureTask old = fileName2Data.putIfAbsent(fName, data);
if(old==null){
data = old;
}else{
exec.execute(data);
}
}
String d = data.get();
//process with data
}
private FutureTask newFutureTask(final String file){
return new FutureTask(new Callable<String>(){
public String call(){
return readFromFile(file);
}
private String readFromFile(String file){return "";}
}
}
}
多线程的常见应用场景:
后台任务,例如:定时向大量(100w以上)的用户发送邮件; 异步处理,例如:发微博、记录日志等; 分布式计算
推荐阅读:
微信扫描二维码,关注我的公众号
朕已阅