java并发编程实践 笔记(1)
线程安全 什么是线程安全(thread-safe)? 一个类,如果能够在多线程并发访问的环境下(不管线程访问的顺序)正确表现自己的行为,并且无需外部调用添加任何同步之类的操作,这个类就是线程安全的。
这个正确性可以这么理解,就是说多线程访问的结果不会不同于单线程的访问。
线程安全的类不需要外部调用提供任何附加的同步。 无状态(stateless)的类永远是线程安全的。
什么是无状态的类?没有实例变量(field),也没有引用其它类的field。 原子性 A race condition occurs when the correctness of a computation depends on the relative timing or interleaving of multiple threads by the runtime; in other words, when getting the right answer relies on lucky timing. 最常见的race condition是check-and-act。要防止这种race condition,我们需要原子性的操作。什么是原子性呢,就是说,你这个操作在执行的过程中,对于你操作的状态上其它的操作(包括你自己)要么全都执行完了,要么还没开始。
想说句通顺的中国话怎么这么难啊,还是给出原文吧: Operations A and B are atomic with respect to each other if, from the perspective of a thread executing A, when another thread executes B, either all of B has executed or none of it has. An atomic operation is one that is atomic with respect to all operations, including itself, that operate on the same state. 来个例子 @NotThreadSafe
public class UnsafeCountingFactorizer implements Servlet {
private long count = 0;
public long getCount() { return count; }
public void service(ServletRequest req, ServletResponse resp) {
BigInteger i = extractfromRequest(req);
BigInteger[] factors = factor(i);
++count;
encodeIntoResponse(resp, factors);
}
}
@ThreadSafe
public class CountingFactorizer implements Servlet {
private final AtomicLong count = new AtomicLong(0);
public long getCount() { return count.get(); }
public void service(ServletRequest req, ServletResponse resp) {
BigInteger i = extractfromRequest(req);
BigInteger[] factors = factor(i);
count.incrementAndGet();
相关文档:
今天是写第一篇传智播客教程日志,也是我看
JavaScript
视频的第一天。
先说缘由吧。大三还有三个月就要结束了,可我还没有感觉到自己能够有足够的能力找到份好工作,大学期间学到的都是些皮毛和理论,我不想到了找工作的时候,面试官问我会
XXX
吗?我说不会。因此我想通过培训增加自己的竞争力。我报了本地的一家
I ......
正多边形中最长的对角线就是主对角线,其余的对角线就是副对角线
lang 是 language(语言) 的简写
是java中常用方法最多的包
包含常用类
Runnable接口,只有一个方法run()
exit(int status)
终止当前正在运行的 Jav ......
0. 学习一章掌握一张,然后再不断的用。
1. 找一些比较经典的例子,源码(源码爱好者), 每个例子比较集中一种编程思想而设计的,比如在我的实践当中,我曾经学习过一个很经 典的例子就是用Java实现的HotDraw(源自SmallTalk),你可以用rolemodel或hotdraw在 搜索引擎上找一下,我记不大清 ......
public static void CentreWnd(Shell shell){
int width = shell.getMonitor().getClientArea().width;
int height = shell.getMonitor().getClientArea().height;
int x = shell.getSize().x;
int y = shell.getSize().y;
if (x > width) {
shell.getSize().x = width;
}
if (y > height) ......
同样的程序,在别人的电脑上都可以用,在我的电脑上却无论如何都通不过,郁闷啊。
昨天遇到一个问题搞了一天都没有解决,
这个程序在别人的电脑上用都可以通过,只有在我的电脑上无法通过
,我一开始装的是JDK6.0,后来卸载了装成了JDK5.0(为了和所学教程保持一致,
以及我宿舍通过测试的机器也是装的JDK5.0),
但是 ......