当前位置:编程学习 > JSP >>

Java Thread Programming 1.7 - Concurrent Access to

When multiple threads are interacting with an object, controls need to be in place to ensure that the threads don’t adversely affect one another. This chapter deals with issues that can introduce subtle errors in your application. An application that fails to safely control concurrent access can work properly most of the time—maybe nearly all the time—but will occasionally produce erroneous results. This makes the understanding and disciplined use of the information in this chapter critical to writing truly thread-safe applications that work properly all the time.
如果你的系统出现了莫名其妙的问题,很有可能是并发访问的问题哦
volatile Member Variable Modifier
The Java Language Specification indicates that for optimal speed, individual threads are permitted to keep a working copy of shared member variables and only reconcile them with the shared original occasionally. To be more accurate, the word “occasionally” in the last sentence should be replaced with “when a thread enters or leaves a synchronized block of code.” I’ll tell you more about synchronized blocks later in this chapter. When only one thread is interacting with the member variables of an object, this optimization works very well and can allow for faster execution. When two (or more) threads are simultaneously working with an object, care must be taken to ensure that changes made to a shared member variable by one thread are seen by the other.
Java规范中说明,为了优化速度,每个线程都拥有共享成员变量的一个拷贝,当线程开始或结束一个同步代码块时,才回写变量值。当单线程时,这种机制很好的工作,可以获得更高的性能,但是多个线程协同工作时,必须考虑,被一个线程改变的公共变量要被其他线程知道。
The volatile keyword is used as a modifier on member variables to force individual threads to reread the variable’s value from shared memory every time the variable is accessed. In addition, individual threads are forced to write changes back to shared memory as soon as they occur. This way, two different threads always see the same value for a member variable at any particular time. Chances are that most of you expected this behavior from the Java VM already. In fact, many experienced Java developers don’t understand when the use of volatile is necessary.
补充:Jsp教程,Java技巧及代码
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,