package org.example.concurrency.test.n7;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* @author huskyui
*/
@Slf4j
public class TestStarvation {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.execute(()->{
log.debug("处理点餐");
Future<String> f = pool.submit(() -> {
log.debug("做菜");
return "123";
});
try{
log.debug("上菜 {}",f.get());
}catch (Exception e){
e.printStackTrace();
}
});
pool.execute(()->{
log.debug("处理点餐");
Future<String> f = pool.submit(() -> {
log.debug("做菜");
return "456";
});
try{
log.debug("上菜 {}",f.get());
}catch (Exception e){
e.printStackTrace();
}
});
}
}
问题
解决方法一
增加线程数
但有缺陷,上述代码只是模拟两个并发情况下,如果是三个,也就又解决不了了
正确处理
不同的任务,交给不同的线程池处理
ExecutorService waiterPool = Executors.newFixedThreadPool(1);
ExecutorService cookPool = Executors.newFixedThreadPool(1);
waiterPool.execute(()->{
log.debug("处理点餐");
Future<String> f = cookPool.submit(() -> {
log.debug("做菜");
return "123";
});
try{
log.debug("上菜 {}",f.get());
}catch (Exception e){
e.printStackTrace();
}
});
waiterPool.execute(()->{
log.debug("处理点餐");
Future<String> f = cookPool.submit(() -> {
log.debug("做菜");
return "456";
});
try{
log.debug("上菜 {}",f.get());
}catch (Exception e){
e.printStackTrace();
}
});