Four Ways of sychronized keywords
Sychronized method () {}
Sychronized (objectreference) {/*block*/}
Static Synchronized Method () {}
Sychronized (Classname.class)
where 1 and 2 represent the current object of the lock, that is, an object is a lock, and 3 and 4 represent the lock class, that is, the lock of this class.
Note that sychronized method () is not a lock function, but rather a lock object, namely: If two of the methods in this class are sychronized, then as long as two threads share one of the reference of the class, each one of these two methods is called This object lock is synchronized, regardless of whether or not the same method is used. 3 and 4 of the lock class, that is, the different reference of the class call the sychronized section of the drum to be controlled by the class lock.
Also, if the sequence of two function calls cannot be interrupted, a special lock object can be used to accomplish this task:
class MyLock
{
synchronized getLock()
{
//####还没写完
}
}
Five levels See effective Java Item 52:document thread safety
Immutable immutable objects
Thread-safe thread safe, can be used with ease, such as Java.util.Timer
Conditionally Thread-safe conditional thread-safe, such as vectors and Hashtable, are generally safe, unless the order between several method invocations cannot be interrupted, an additional lock can be used to complete
Thread-compatible can use synchronized (objectreference) to assist in the completion of calls to threads
Thread-hostile not safe.
Wait & Notifyall
Use a wait in a loop instead of a notify Notifyall
Pipe
Java also has pipe, four classes: PipedInputStream, Pipedinputreader, PipedOutputStream, Pipedoutputwriter below is a section of producer consumer Code (excerpt from the core JAVAII):
/* set up pipes */
PipedOutputStream pout1 = new PipedOutputStream();
PipedInputStream pin1 = new PipedInputStream(pout1);
PipedOutputStream pout2 = new PipedOutputStream();
PipedInputStream pin2 = new PipedInputStream(pout2);
/* construct threads */
Producer prod = new Producer(pout1);
Filter filt = new Filter(pin1, pout2);
Consumer cons = new Consumer(pin2);
/* start threads */
prod.start();
filt.start();
cons.start();