静态工具方法的并发控制

静态工具方法并发时候不能简单的用同步关键字来同步方法,因为静态方法是类级别的方法,锁定的是这个类class本身,这样的结果就是任何一个同步的静态方法运行,,都会导致其他同步方法调用的阻塞。这个也是问题所在。

这里给出一个简单的方法来避免这个问题:

通过给每个方法一个锁来控制并发,就可以巧妙的解决阻塞问题。

importjava.util.concurrent.locks.Lock;importjava.util.concurrent.locks.ReentrantLock;/***静态工具方法的并发控制**@authorleizhimin2014/7/1917:18*/publicclassTest{privatestaticfinalLocklock1=newReentrantLock();privatestaticfinalLocklock2=newReentrantLock();publicstaticvoidt1()throwsInterruptedException{lock1.lock();System.out.println(Thread.currentThread().getName()+”:t1…”);Thread.sleep(500L);lock1.unlock();}publicstaticvoidt2()throwsInterruptedException{lock2.lock();System.out.println(Thread.currentThread().getName()+”:t2…”);lock2.unlock();}publicstaticvoidmain(String[]args){newThread(newRunnable(){@Overridepublicvoidrun(){try{t1();}catch(InterruptedExceptione){e.printStackTrace();}}}).start();newThread(newRunnable(){@Overridepublicvoidrun(){try{t1();}catch(InterruptedExceptione){e.printStackTrace();}}}).start();newThread(newRunnable(){@Overridepublicvoidrun(){try{t1();}catch(InterruptedExceptione){e.printStackTrace();}}}).start();newThread(newRunnable(){@Overridepublicvoidrun(){try{t2();}catch(InterruptedExceptione){e.printStackTrace();}}}).start();newThread(newRunnable(){@Overridepublicvoidrun(){try{t2();}catch(InterruptedExceptione){e.printStackTrace();}}}).start();newThread(newRunnable(){@Overridepublicvoidrun(){try{t2();}catch(InterruptedExceptione){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…Processfinishedwithexitcode0

本文出自 “熔 岩” 博客,请务必保留此出处

想念我的时候,不要忘记我也在想念你。

静态工具方法的并发控制

相关文章:

你感兴趣的文章:

标签云: