Thread.sleep
causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.synchronized
keyword with a constructor is a syntax error. synchronized
methods. (An important exception: final
fields, which cannot be modified after the object is constructed, can be safely read through non-synchronized methods, once the object is constructed) This strategy is effective, but can present problems with liveness, Locks In Synchronized Methods
When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.
You might wonder what happens when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the Class
object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class.
Synchronized Statements
Another way to create synchronized code is with synchronized statements. Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock:
public void addName(String name) { synchronized(this) { lastName = name; nameCount++; } nameList.add(name); }
volatile
variables reduces the risk of memory consistency errors, because any write to avolatile
variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile
variable are always visible to other threads. What's more, it also means that when a thread reads a volatile
variable, it sees not just the latest change to the volatile
, but also the side effects of the code that led up the change.
No comments:
Post a Comment