静态工具方法并发时候不能简单的用同步关键字来同步方法,因为静态方法是类级别的方法,锁定的是这个类class本身,这样的结果就是任何一个同步的静态方法运行,都会导致其他同步方法调用的阻塞。这个也是问题所在。
这里给出一个简单的方法来避免这个问题:
通过给每个方法一个锁来控制并发,就可以巧妙的解决阻塞问题。
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 静态工具方法的并发控制 * * @author leizhimin 2014/7/19 17:18 */ 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