Original address: http://blog.csdn.net/huang_xw/article/details/7318554
/** * @Description: Two threads (thread 1 and thread 2) access the internal synchronization method of the same object SYN * Results: Thread 1 accesses the synchronization Method SYN () of the object sameobj, while thread 2 accesses the synchronous Method SYN () blocking in the object sameobj.
or thread 2 access, thread 1 is blocked.
* Conclusion: When different threads access the same synchronization method for the same object, the threads are mutually exclusive.
* @author Snoopy * @blog HTTP://BLOG.CSDN.NET/HUANG_XW/package Basic.b_syn;
Import Org.apache.log4j.Logger;
Import Sun.management.snmp.jvminstr.JvmThreadInstanceEntryImpl.ThreadStateMap;
public class Testsynb {private static Logger Logger = Logger.getlogger (Testsynb.class);
Thread 1 Static class T1 implements Runnable {TESTSYNB s;
Public T1 (Testsynb sameobj) {this.s = Sameobj;
//thread 1 Access synchronization Method SYN () public void Run () {logger.debug ("Start thread 1 ...");
S.syn ();
Logger.debug ("Exit thread 1 ....");
}//thread 2 static class T2 implements Runnable {TESTSYNB s;
Public T2 (Testsynb sameobj) {this.s = Sameobj;
//Thread 2 Access synchronization Method SYN () public void Run () {logger.debug ("Start thread 2 ...");
S.syn ();
Logger.debug ("Exit thread 2 ...."); }//object's Sync method public synchronized void Syn () {String threadstr = Thread.CurrentThread (). GetName ();
Logger.debug ("▲▲▲▲▲▲" + threadstr + "Start Access Sync method");
try {logger.debug (threadstr + "Accessing Sync method!!!");
Thread.Sleep (3000);
catch (Interruptedexception e) {e.printstacktrace ();
} logger.debug ("▲▲▲▲▲▲" + threadstr + "Exit Sync method");
public static void Main (string[] args) {//This is the same object that multithreading will access testsynb sameobj = new Testsynb ();
Thread 1 accesses the synchronization Method SYN (), and thread 2 also accesses the synchronization Method SYN ().
thread T1 = new Thread (new T1 (sameobj), "Thread 1");
Thread t2 = new Thread (new T2 (sameobj), "Thread 2");
T1.start ();
T2.start (); }
}
Execution results:
0 [Thread 2] DEBUG Basic.b_syn. TESTSYNB-Start thread 2
..... 0 [Thread 1] DEBUG Basic.b_syn. TESTSYNB-Start thread 1
..... 1 [Thread 2] DEBUG Basic.b_syn. TESTSYNB-▲▲▲▲▲▲ Thread 2 begins access to synchronization method
1 [Thread 2] DEBUG Basic.b_syn. TESTSYNB-Thread 2 is accessing the synchronization method!!!
3001 [Thread 2] DEBUG Basic.b_syn. TESTSYNB-▲▲▲▲▲▲ Thread 2 exits synchronization method
3001 [Thread 1] DEBUG Basic.b_syn. TESTSYNB-▲▲▲▲▲▲ Thread 1 begins access to synchronization method
3001 [Thread 1] DEBUG Basic.b_syn. TESTSYNB-Thread 1 is accessing the synchronization method!!!
3001 [Thread 2] DEBUG Basic.b_syn. TESTSYNB-Exit thread 2
..... 6001 [Thread 1] DEBUG Basic.b_syn. TESTSYNB-▲▲▲▲▲▲ Thread 1 Exits synchronization method
6001 [Thread 1] DEBUG Basic.b_syn. TESTSYNB-Exit Thread 1 .....