Synchronous to Java, some understanding Kingfish 2005 ------------------------------------------- ---------------- Basic concept: Every Object will have 1 lock. Synchronization is serial using some resources.
(Note: The following examples have omitted unnecessary code in order to highlight the focus. In particular, some member variables are saved, which is the object that needs to be synchronized.)
1. Synchronize sharing and variable data in multi-threads. There is no need to synchronize for local variables in functions. For non-variable data, it is not necessary to synchronize.
Access shared variable data in multi-thread is necessary.
2. Synchronized can be used in a single thread, and it can be nested, but meaningless. Class test {public static void main (string [] args) {test t = new test (); synchronized (t) {synchronized (t) { System.out.println ("OK!");}}}} 3. Lock Class test {public synchronized void f1 () {// do sometying here}
The F1 () and F2 () {// DO Something Here}} The upper F1 () and F2 () effects are consistent, and the lock acquired by Synchronized is a lock of a Test, such as: Test T = New Test (); Thread A When T.f2 (), thread b cannot enter T.f1 () until T.f2 () ends.
Role: Synchronize when accessing the same instance of TEST in multi-threads.
4. Class lock Class test {final static object o = new object ();
public static synchronized void f1 () {// do something here} public static void f2 () {synchronized (Test.class) {// do something here}} public static void f3 () {try {synchronized (Class.forName ( "TEST")) {// do something here}} catch (classnotfoundexception ex) {}} public static void g () {synchronized (o) {// do something heren}}}}}}
The upper F1 (), F2 (), F3 (), g () effect is consistent F1 (), f2 (), and the lock in the Synchronized acquired is the lock of Test.class. G () is an object that you generate yourself o Synchronize using O locks: Synchronization methods of accessing such or such instances in multithreading. Singleton mode Lazily Initializing belongs to this class.
5. static method class test {private static int v = 0;
Public Static Void F1 () {// do something, but in the function is not used in V} public synchronized static void f2 () {// do sometying, the V is read / written in the function.}}
When a list of TEST is used in multi-thread, (1) f1 () is thread secure, and does not require synchronization (2) F2 () this static variable in this static method, so you need to synchronize.
6. Synchronize the thread's Run (). // ...}} This example will have a problem, perform Run () (internal in loop), and cannot perform f ()
Class test extends thread {public synchronized void run () {// do something}} This example is basically useless because run () is usually performed by New Test (). START (). Because the Test instance is different, the lock Also different.
-------------------------------------------------- ----------------------- If there is any problem, please refer to you!