Four ways Sychronized keyword
Sychronized method () {} sychronized (ObjectReference) {/ * block * /} static synchronized method () {} sychronized (classname.class)
Where 1 and 2 are representative lock current objects, that is, an object is a lock, 3 and 4 representative locks, that is, the lock of this class should be noted that sychronized method () is not locking this function, but a lock object, ie: If there are two methods in this class, it is sychronized, then as long as there are two threads share a Reference Reference, one of these two methods, regardless of whether it is the same method, it will be synchronized with this object lock. The 3 and 4 classes of the lock, that is, the different reference of this class calls the Sychronized section of the Sychronized section. It is also controlled by the class lock. If the order of the two functions calls cannot be interrupted, then there is a special Lock object to complete this task: class mylock {synchronized getLock () {// #### has not been written}}
Five levels see Effective Java Item 52: Document Thread Safety
Immutable Unremntered Object Thread-Safe Thread Security, you can use, such as java.util.timer conditionally thread-Safe condition thread secure, such as Vector and HashTable, generally secure, unless there are several method calls Can't be interrupted, you can use the additional lock to complete thread-compatible to help complete the call to thread through Thread-hostile is not safe.
Wait & NotifyAll
Use WAIAll in the cycle instead of notify
Pipe
There is also a PIPE in Java, four classes: PipedinputStream, PipedInputReader, PipedputStream, Pipedputstream, below is the code of producer consumers (from 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 Producter (Pout1); Filter Filt = New Filter (PIN1, Pout2); Consumer Cons = New Consumer (PIN2); / * START THREADS * / PROD.START (); Filt (); Cons.Start ();
note
Long and double are two special 咚咚: Java reads them twice, so you need to synchronize