欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

《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