【翻译二十三】java-并发程序之随机数和参考资料与问题(本系列完)
Concurrent Random Numbers
In JDK 7, java.util.concurrent includes a convenience class, ThreadLocalRandom, for applications that expect to use random numbers from multiple threads or ForkJoinTasks.
For concurrent access, using ThreadLocalRandom instead of Math.random() results in less contention and, ultimately, better performance.
All you need to do is call ThreadLocalRandom.current(), then call one of its methods to retrieve a random number. Here is one example:
int r = ThreadLocalRandom.current() .nextInt(4, 77);
译文:
在JDK 7中,java.util.concurrent包括了一个便利的类,ThreadLocalRandom,对于应用程序希望用随机数在多线程中或者ForkJoinTasks.
对于并发使用,利用ThreadLocalRandom代替Math.Random()导致一些争议,基本上,性能上更好。
所有你要做的是调用ThreadLocalRandom.current(),然后调用它的方法重新获得一个随机数。这是一个实例:
int r = ThreadLocalRandom.current() .nextInt(4, 77);
For Further Reading
- Concurrent Programming in Java: Design Principles and Pattern (2nd Edition) by Doug Lea. A comprehensive work by a leading expert, who's also the architect of the Java platform's concurrency framework.
- Java Concurrency in Practice by Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, and Doug Lea. A practical guide designed to be accessible to the novice.
- Effective Java Programming Language Guide (2nd Edition) by Joshua Bloch. Though this is a general programming guide, its chapter on threads contains essential "best practices" for concurrent programming.
- Concurrency: State Models & Java Programs (2nd Edition), by Jeff Magee and Jeff Kramer. An introduction to concurrent programming through a combination of modeling and practical examples.
- Java Concurrent Animated: Animations that show usage of concurrency features.
译文:
进一步阅读
- Doug Lea的《Java的并发编程:设计原则和模式》(第二版)。一个领先的专家做了一些全面的工作。也是Java并发平台的架构师。
- Brian Goetz,Tim Peierls,Joshua Bloch,Joseph Bowbeer,David Holmes,和Doug Lea的《Java 并发实例》。
- Joshua Bloch的《高效的Java语言编程指南》(第二版),它关于线程的章节包含基本的并发编程的“最好实例”
- Jeff Magee和Jeff Kramer的《并发:状态模型与Java程序》(第二版),一个通过实例和模型来介绍并发程序的书。
- 《Java 并发动画》:展示并发特性的动画。
Questions and Exercises: Concurrency
Questions
- Can you pass a
Threadobject toExecutor.execute? Would such an invocation make sense?
Exercises
- Compile and run
BadThreads.java:public class BadThreads { static String message; private static class CorrectorThread
extends Thread { public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {}
// Key statement 1:
message = "Mares do eat oats.";
}
} public static void main(String args[])
throws InterruptedException { (new CorrectorThread()).start();
message = "Mares do not eat oats.";
Thread.sleep(2000);
// Key statement 2:
System.out.println(message);
}
}The application should print out "Mares do eat oats." Is it guaranteed to always do this? If not, why not? Would it help to change the parameters of the two invocations of
Sleep? How would you guarantee that all changes tomessagewill be visible in the main thread? - Modify the producer-consumer example in Guarded Blocks to use a standard library class instead of the
Dropclass.
译文:
问题和练习:并发
问题:
1.你能用一个线程对象来执行Executor.execute吗?这样调用有意义吗?
练习:
1.编译和运行BadThreads.java:
public class BadThreads {
static String message;
private static class CorrectorThread
extends Thread {
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {}
// Key statement 1:
message = "Mares do eat oats.";
}
}
public static void main(String args[])
throws InterruptedException {
(new CorrectorThread()).start();
message = "Mares do not eat oats.";
Thread.sleep(2000);
// Key statement 2:
System.out.println(message);
}
}
这个程序应该打印出"Mares do eat oats."它是否保证一直这样做?如果不,为什么?它是否会改变这个睡眠参数?你会如何保证在主程序中所有的message都是可见的?
2.修改 Guarded Blocks节中生产者-消费者程序利用标准的类库程序代替Drop类。
Answers to Questions and Exercises: Concurrency
Questions
- Question: Can you pass a
Threadobject toExecutor.execute? Would such an invocation make sense? Why or why not?Answer:
Threadimplements theRunnableinterface, so you can pass an instance ofThreadtoExecutor.execute. However it doesn't make sense to useThreadobjects this way. If the object is directly instantiated fromThread, itsrunmethod doesn't do anything. You can define a subclass ofThreadwith a usefulrunmethod — but such a class would implement features that the executor would not use.
Exercises
- Exercise: Compile and run
BadThreads.java:public class BadThreads { static String message; private static class CorrectorThread
extends Thread { public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {}
// Key statement 1:
message = "Mares do eat oats.";
}
} public static void main(String args[])
throws InterruptedException { (new CorrectorThread()).start();
message = "Mares do not eat oats.";
Thread.sleep(2000);
// Key statement 2:
System.out.println(message);
}
}The application should print out "Mares do eat oats." Is it guaranteed to always do this? If not, why not? Would it help to change the parameters of the two invocations of
Sleep? How would you guarantee that all changes tomessagewill be visible to the main thread?Solution: The program will almost always print out "Mares do eat oats." However, this result is not guaranteed, because there is no happens-before relationship between "Key statement 1" and "Key statment 2". This is true even if "Key statement 1" actually executes before "Key statement 2" — remember, a happens-before relationship is about visibility, not sequence.
There are two ways you can guarantee that all changes to
messagewill be visible to the main thread:- In the main thread, retain a reference to the
CorrectorThreadinstance. Then invokejoinon that instance before referring tomessage - Encapsulate
messagein an object with synchronized methods. Never referencemessageexcept through those methods.
Both of these techniques establish the necessary happens-before relationship, making changes to
messagevisible.A third technique is to simply declare
messageasvolatile. This guarantees that any write tomessage(as in "Key statement 1") will have a happens-before relationship with any subsequent reads ofmessage(as in "Key statement 2"). But it does not guarantee that "Key statement 1" willliterally happen before "Key statement 2". They will probably happen in sequence, but because of scheduling uncertainities and the unknown granularity ofsleep, this is not guaranteed.Changing the arguments of the two
sleepinvocations does not help either, since this does nothing to guarantee a happens-before relationship. - In the main thread, retain a reference to the
- Exercise: Modify the producer-consumer example in Guarded Blocks to use a standard library class instead of the
Dropclass.Solution: The
java.util.concurrent.BlockingQueueinterface defines agetmethod that blocks if the queue is empty, and aputmethods that blocks if the queue is full. These are effectively the same operations defined byDrop— except thatDropis not a queue! However, there's another way of looking at Drop: it's a queue with a capacity of zero. Since there's no room in the queue for any elements, everygetblocks until the correspondingtakeand everytakeblocks until the correspondingget. There is an implementation ofBlockingQueuewith precisely this behavior:java.util.concurrent.SynchronousQueue.BlockingQueueis almost a drop-in replacement forDrop. The main problem inProduceris that withBlockingQueue, theputandgetmethods throwInterruptedException. This means that the existingtrymust be moved up a level:import java.util.Random;
import java.util.concurrent.BlockingQueue; public class Producer implements Runnable {
private BlockingQueue<String> drop; public Producer(BlockingQueue<String> drop) {
this.drop = drop;
} public void run() {
String importantInfo[] = {
"Mares eat oats",
"Does eat oats",
"Little lambs eat ivy",
"A kid will eat ivy too"
};
Random random = new Random(); try {
for (int i = 0;
i < importantInfo.length;
i++) {
drop.put(importantInfo[i]);
Thread.sleep(random.nextInt(5000));
}
drop.put("DONE");
} catch (InterruptedException e) {}
}
}Similar changes are required for
Consumer:import java.util.Random;
import java.util.concurrent.BlockingQueue; public class Consumer implements Runnable {
private BlockingQueue<String> drop; public Consumer(BlockingQueue<String> drop) {
this.drop = drop;
} public void run() {
Random random = new Random();
try {
for (String message = drop.take();
! message.equals("DONE");
message = drop.take()) {
System.out.format("MESSAGE RECEIVED: %s%n",
message);
Thread.sleep(random.nextInt(5000));
}
} catch (InterruptedException e) {}
}
}For
ProducerConsumerExample, we simply change the declaration for thedropobject:import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue; public class ProducerConsumerExample {
public static void main(String[] args) {
BlockingQueue<String> drop =
new SynchronousQueue<String> ();
(new Thread(new Producer(drop))).start();
(new Thread(new Consumer(drop))).start();
}
}
answer 就不翻了
^_^本系列终于翻译完结了^_^撒花^_^高兴^_^
【翻译二十三】java-并发程序之随机数和参考资料与问题(本系列完)的更多相关文章
- 二十三、并发编程之深入解析Condition源码
二十三.并发编程之深入解析Condition源码 一.Condition简介 1.Object的wait和notify/notifyAll方法与Condition区别 任何一个java对象都继承于 ...
- 猫头鹰的深夜翻译:核心JAVA并发一
简介 从创建以来,JAVA就支持核心的并发概念如线程和锁.这篇文章会帮助从事多线程编程的JAVA开发人员理解核心的并发概念以及如何使用它们. (博主将在其中加上自己的理解以及自己想出的例子作为补充) ...
- 《Java并发编程的艺术》读书笔记:二、Java并发机制的底层实现原理
二.Java并发机制底层实现原理 这里是我的<Java并发编程的艺术>读书笔记的第二篇,对前文有兴趣的朋友可以去这里看第一篇:一.并发编程的目的与挑战 有兴趣讨论的朋友可以给我留言! 1. ...
- 20155301第十二周java课程程序
20155301第十二周java课程程序 内容一:在IDEA中以TDD的方式对String类和Arrays类进行学习 测试相关方法的正常,错误和边界情况 String类 charAt split Ar ...
- java并发程序和共享对象实用策略
java并发程序和共享对象实用策略 在并发程序中使用和共享对象时,可以使用一些实用的策略,包括: 线程封闭 只读共享.共享的只读对象可以由多个线程并发访问,但任何线程都不能修改它.共享的只读对象包括不 ...
- Java并发程序设计(二)Java并行程序基础
Java并行程序基础 一.线程的生命周期 其中blocked和waiting的区别: 作者:赵老师链接:https://www.zhihu.com/question/27654579/answer/1 ...
- Java 并发系列之二:java 并发机制的底层实现原理
1. 处理器实现原子操作 2. volatile /** 补充: 主要作用:内存可见性,是变量在多个线程中可见,修饰变量,解决一写多读的问题. 轻量级的synchronized,不会造成阻塞.性能比s ...
- java并发程序——并发容器
概述 java cocurrent包提供了很多并发容器,在提供并发控制的前提下,通过优化,提升性能.本文主要讨论常见的并发容器的实现机制和绝妙之处,但并不会对所有实现细节面面俱到. 为什么JUC需要提 ...
- 转:【Java并发编程】之二十三:并发新特性—信号量Semaphore(含代码)
载请注明出处:http://blog.csdn.net/ns_code/article/details/17524153 在操作系统中,信号量是个很重要的概念,它在控制进程间的协作方面有着非常重要的作 ...
随机推荐
- opencv中的视频的读入
#include"stdafx.h"#include"opencv2/opencv.hpp" using namespace cv;int g_slider_p ...
- java去除字符串中的空格、回车、换行符、制表符
import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author chzeze * 2016-11-07 */ ...
- 分布式架构 Hadoop 2.7.X 安装和配置
一.安装环境 硬件:虚拟机 操作系统:Ubuntu 14 32位 IP:59.77.132.28主机名:admin安装用户:root 二.安装JDK 安装JDK1.7或者以上版本.这里安装jdk1.7 ...
- JQuery textarea中val(),text()
val()是当前输入框的前台显示内容 text()是原始内容, 调试时浏览器审查元素可以发现如果只改变val(),text()值是不会改变的
- ulimit命令
原文链接 linux下默认是不产生core文件的,要用ulimit -c unlimited放开 概述 系统性能一直是一个受关注的话题,如何通过最简单的设置来实现最有效的性能调优,如何在有限资源的条件 ...
- 100m和1000m网线的常见制作方法
100m和1000m网线的常见制作方法 100m和1000m网线的常见制作方法: 5类线(100m)的制作: a: 绿白(3).绿(6).橙白(1).蓝(4).蓝白(5).橙(2).棕白(7).棕(8 ...
- js中 map 遍历数组
map 方法会迭代数组中的每一个元素,并根据回调函数来处理每一个元素,最后返回一个新数组.注意,这个方法不会改变原始数组. 在我们的例子中,回调函数只有一个参数,即数组中元素的值 (val 参数) , ...
- 【hadoop2.6.0】利用JAVA API 实现数据上传
原本的目的是想模拟一个流的上传过程,就是一边生成数据,一边存储数据,因为能用上HADOOP通常情况下原本数据的大小就大到本地硬盘存不下.这一般是通过把数据先一部分一部分的缓冲到本地的某个文件夹下,hd ...
- 【python】dict的注意事项
1. key不能用list和set 由于列表是易变的,故不可做key.如果使用会报错 但是元组可以做key 2.遍历方法 for key in somedict: pass 速度快,但是如果要删除元素 ...
- 用css解决iframe的自适应问题(跨域下同样有用)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xht ...