《effective java》之九:并发 博客分类: Java effective
程序员文章站
2024-02-15 08:50:58
...
第66条:同步访问共享的可变数据:
使用volatile可以在两个线程中通信
public class StopThread { private static volatile boolean stopRequested; public static void main(String[] args) throws InterruptedException { Thread backgroundThread = new Thread(new Runnable() { public void run() { int i = 0; while (!stopRequested) i++; } }); backgroundThread.start(); TimeUnit.SECONDS.sleep(1); stopRequested = true; } }
第67条:避免过度同步:
千万不要从同步区域内部调用外来方法。尽量限制同步区域内部的工作量。除非迫不得已,否则尽量不要在内部同步类,而是应该让客户在必要的时候从外部同步。
第68条:executor和task优先于线程:
第69条:并发工具优于wait和notify
public class ConcurrentTimer { private ConcurrentTimer() { } // Noninstantiable public static long time(Executor executor, int concurrency, final Runnable action) throws InterruptedException { final CountDownLatch ready = new CountDownLatch(concurrency); final CountDownLatch start = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(concurrency); for (int i = 0; i < concurrency; i++) { executor.execute(new Runnable() { public void run() { ready.countDown(); // Tell timer we're ready try { start.await(); // Wait till peers are ready action.run(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { done.countDown(); // Tell timer we're done } } }); } ready.await(); // Wait for all workers to be ready long startNanos = System.nanoTime(); start.countDown(); // And they're off! done.await(); // Wait for all workers to finish return System.nanoTime() - startNanos; } }
第70条:线程安全性的文档化:
第71条:慎用延迟初始化:
第72条:不要依赖于线程调度器:
第73条:避免使用线程组:
本人博客已搬家,新地址为:http://yidao620c.github.io/
推荐阅读
-
《effective java》之十:序列化 博客分类: Java effective
-
《effective java》之七:方法 博客分类: Java effective
-
Effective Java读书笔试之创建和销毁对象 博客分类: effective java effectivejava
-
《effective java》之六:方法 博客分类: Java effective
-
《effective java》之九:并发 博客分类: Java effective
-
volatile关键字 博客分类: Java-并发
-
volatile关键字 博客分类: Java-并发
-
《程序员 Java天下事,2010.01 低碳时代之Java风云》8卜被退稿 博客分类: Java JavaJVMSpring编程算法
-
停止启用了安全性的WAS Server而不手动输入密码之第二种选择 博客分类: Java SOAPWebsphereIBMPHPBBS
-
WAS证书过期替换之独立WAS Server之文字操作版 博客分类: Java IBM配置管理应用服务器脚本