When the static tool method is concurrent, you cannot simply use the synchronization keyword to synchronize the method, because the static method is a Class-level method and the lock is the class itself, the result is that any static synchronous method running will cause blocking of other synchronous method calls. This is also the problem.
Here is a simple method to avoid this problem:
By giving each method a lock to control concurrency, You Can cleverly solve the blocking problem.
Import Java. util. concurrent. locks. lock; import Java. util. concurrent. locks. reentrantlock;/*** concurrency control of static tool Methods ** @ author leizhimin */public class test {Private Static final lock lock1 = new reentrantlock (); private Static final lock lock2 = new reentrantlock (); public static void T1 () throws interruptedexception {lock1.lock (); system. out. println (thread. currentthread (). getname () + ": t1... "); thread. sleep (500l); lock1.unlock ();} public static void T2 () throws interruptedexception {lock2.lock (); system. out. println (thread. currentthread (). getname () + ": t2... "); lock2.unlock ();} public static void main (string [] ARGs) {New thread (New runnable () {@ override public void run () {try {T1 ();} catch (interruptedexception e) {e. printstacktrace ();}}}). start (); New thread (New runnable () {@ override public void run () {try {T1 ();} catch (interruptedexception e) {e. printstacktrace ();}}}). start (); New thread (New runnable () {@ override public void run () {try {T1 ();} catch (interruptedexception e) {e. printstacktrace ();}}}). start (); New thread (New runnable () {@ override public void run () {try {T2 ();} catch (interruptedexception e) {e. printstacktrace ();}}}). start (); New thread (New runnable () {@ override public void run () {try {T2 ();} catch (interruptedexception e) {e. printstacktrace ();}}}). start (); New thread (New runnable () {@ override public void run () {try {T2 ();} catch (interruptedexception e) {e. printstacktrace ();}}}). start ();}}
D:\jdk1.7.0_55\bin\java 。。。Thread-0: t1...Thread-3: t2...Thread-4: t2...Thread-5: t2...Thread-2: t1...Thread-1: t1...Process finished with exit code 0
This article is from the "melyan" blog, please be sure to keep this source http://lavasoft.blog.51cto.com/62575/1540088