publicclassConcurrencyTest{ privatestaticfinallong count = 100000001; publicstaticvoidmain(String[] args)throws InterruptedException { concurrenct(); serial(); } privatestaticvoidconcurrenct()throws InterruptedException { long start = System.currentTimeMillis(); Thread thread = new Thread(new Runnable() { @Overridepublicvoidrun(){ int a = 0; for (long i = 0; i < count; i++) { a += 5; } } }); thread.start(); int b = 0; for (long i = 0; i < count; i++) { b--; } long time = System.currentTimeMillis() - start; thread.join(); System.out.println("concurrency: " + time + "ms, b = " + b); } privatestaticvoidserial(){ long start = System.currentTimeMillis(); int a = 0; for (long i = 0; i < count; i++) { a += 5; } int b = 0; for (long i = 0; i < count; i++) { b--; } long time = System.currentTimeMillis() - start; System.out.println("serial: " + time + "ms, b = " + b); } }
循环次数
serial/ms
concurrent/ms
一亿
91
51
一千万
14
10
一百万
5
5
十万
2
3
一万
0
0
1.2 如何减少上下文切换
无锁并发编程:多线程竞争锁时,会引起上下文切换。因此 Hash 算法通过取模分段,不同的线程处理不同段的数据。 CAS 算法: Atomic 包使用 CAS 算法来更新数据,而不需要加锁。 协程:在单线程里实现多任务的调度,并在单线程里维持多个任务间的切换。