Java5中Lock对象实现同步的效果,而且使用上更方便。
1.ReentrantLock类的使用。
2.ReentrantReadWriteLock类的使用。
ReentrantLock能达到synchronized的效果,且扩展功能也更加强大。
例如:嗅探锁定,多路分支通知等。
使用ReentrantLock实现同步:
package org.test.t8.t_1;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class MyService {
private Lock lock = new ReentrantLock();
public void methodA() {
try {
lock.lock();
System.out.println("methodA begin ThreadName="
+ Thread.currentThread().getName() + " time=" +
System.currentTimeMillis());
Thread.sleep(5000);
System.out.println("methodA end ThreadName="
+ Thread.currentThread().getName() + " time=" +
System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
public void methodB() {
try {
lock.lock();
System.out.println("methodB begin ThreadName="
+ Thread.currentThread().getName() + " time=" +
System.currentTimeMillis());
Thread.sleep(5000);
System.out.println("methodB end ThreadName="
+ Thread.currentThread().getName() + " time=" +
System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException{
MyService service = new MyService();
ThreadA a = new ThreadA(service);
a.setName("A");
a.start();
ThreadAA aa = new ThreadAA(service);
aa.setName("AA");
aa.start();
ThreadB b = new ThreadB(service);
b.setName("B");
b.start();
ThreadBB bb = new ThreadBB(service);
bb.setName("BB");
bb.start();
}
}
调用lock.lock()的线程就持有了对象监视器,其他线程只有等待锁被释放时再次争抢。
效果和使用synchronized一样,线程之间还是按照顺序执行的。