【发布时间】:2017-08-20 02:57:41
【问题描述】:
我在玩 java 多线程代码。我创建了一个带有固定线程池的执行器服务。我按顺序提交两个任务。我试图用 Thread.sleep 让第一个任务变得很长。我在想这两个任务将并行运行。但是,当我运行程序时,程序会等待一段时间,然后打印 A B,这意味着编译器首先完成了第一个任务,然后再执行第二个任务。其实,我是期待的,因为第二个任务是一个短任务,它会在第一个任务之前完成。请解释一下?
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10);
Map<String, String> map = new HashMap<>();
ReadWriteLock lock = new ReentrantReadWriteLock();
executor.submit(() -> {
lock.writeLock().lock();
try {
Thread.sleep(10000);
map.put("boo", "mar");
System.out.println("A");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
lock.writeLock().unlock();
}
});
executor.submit(() -> {
lock.writeLock().lock();
try {
Thread.sleep(1);
map.put("foo", "bar");
System.out.println("B");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
lock.writeLock().unlock();
}
});
executor.shutdown();
}
【问题讨论】:
标签: java multithreading