系列文章:
写给大忙人看的 Java SE 8练习题(一)
写给大忙人看的 Java SE 8练习题(二)
写给大忙人看的 Java SE 8练习题(五)
代码地址:
题目:
1、编写一个程序,跟踪一组线程中最长的字符串。你可以使用一个 AtomicReference 和一个合适的累加器。
public static void main(String[] args) {
String[] list = new String[] {
"djkfs",
"weriew",
"vcnxbm",
"sdnwqer",
"odrteworoe",
"dfowe[er[w",
"pqwrj3221rmgbg,",
"owieroiewtw",
"ropweiotyer",
"oidshfdslfd"
};
AtomicReference<String> atomicReference = new AtomicReference<String>();
BinaryOperator<String> operator = (first, second) -> {
try {
return first.length() > second.length() ? first : second;
} catch (Exception e) {
return first != null ? first : second;
}
};
ExecutorService pools = Executors.newCachedThreadPool();
Arrays.stream(list).forEach(item -> {
pools.submit(() -> {
atomicReference.accumulateAndGet(item, operator);
});
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("the longest world is " + atomicReference.get());
}
2、LongAdder 对生成一个递增的 ID 序列有帮助吗?请说明原因。
没有帮助。LongAdder 是针对高并发场景而设计的,每个线程的数据存放于数组不同的下标位置,当需要总数时才调用 sum 接口计算结果,即 LongAdder 并不关心中间过程的结果。如果生成一个递增的 ID 序列,意味着每次加法都必须得到结果,那么就失去了 LongAdder 的意义。
3、生成 1000 个线程,每个线程会将计数器累加 100000 次,比较使用 AtomicLong 和 LongAdder 所获得的性能。
private static AtomicLong atomicLong = new AtomicLong();
private static LongAdder longAdder = new LongAdder();
public static void main(String[] args) {
BiConsumer<String, Runnable> biConsumer = (item, runnable) -> {
long begin = System.currentTimeMillis();
ExecutorService pool = Executors.newCachedThreadPool();
for (int i = 0; i < 1000; i++) {
pool.submit(() -> {
for (int j = 0; j < 100000; j++) {
runnable.run();
}
});
}
long end = System.currentTimeMillis();
System.out.println("item = " + item + ": " + (end - begin));
};
testAtomicLong(biConsumer);
testLongAddder(biConsumer);
}
private static void testAtomicLong(BiConsumer<String, Runnable> item) {
item.accept("testAtomicLong", () -> atomicLong.incrementAndGet());
}
private static void testLongAddder(BiConsumer<String, Runnable> item) {
item.accept("testLongAddder", () -> longAdder.add(1));
}
4、使用 LongAccumulator 来计算累加元素的最大值或最小值。
public static void main(String[] args) throws InterruptedException {
long[] list = new long