目录
- 1.使用ReentrantLock实现同步:测试一
- 2.使用ReentrantLock实现同步:测试二
- 3.使用Condition实现等待/通知:错误用法与解决
在Java多线程中,可以使用synchronized关键字来实现线程之间同步互斥,但在JDK1.5中心增加了ReentrantLock类也能达到同样的效果,并且在扩展功能上也更加强大,比如具有嗅探锁定、多路分支通知等功能,而且在使用上也比synchronized更加的灵活。
1.使用ReentrantLock实现同步:测试一
既然ReentrantLock类在功能上相比synchronized更多,以下将示例代码:
创建项目4.1.1,创建类MyService.java,代码如下:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class MyService {
private Lock lock = new ReentrantLock();
public void testMethod(){
lock.lock();
for (int i = 0; i < 5; i++) {
System.out.println("ThreadName = "+Thread.currentThread().getName()+(" "+(i+1)));
}
lock.unlock();
}
}
调用ReentrantLock对象的lock()方法获取锁,调用unlock()方法释放锁。
创建类MyThread.java代码如下:
public class MyThread extends Thread{
private MyService service;
public MyThread(MyService service){
super();
this.service = service;
}
@Override
public void run() {
service.testMethod();
}
}
运行类Run.java代码如下:
public class Run {
public static void main(String[] args) {
MyService Service = new MyService();
MyThread m1 = new MyThread(Service);
MyThread m2 = new MyThread(Service);
MyThread m3 = new MyThread(Service);
MyThread m4 = new MyThread(Service);
MyThread m5 = new MyThread(Service);
m1.start();
m2.start();
m3.start();
m4.start();
m5.start();
}
}
程序运行结果如下所示:
ThreadName = Thread-2 1
ThreadName = Thread-2 2
ThreadName = Thread-2 3
ThreadName = Thread-2 4
ThreadName = Thread-2 5
ThreadName = Thread-0 1
ThreadName = Thread-0 2
ThreadName = Thread-0 3
ThreadName = Thread-0 4
ThreadName = Thread-0 5
ThreadName = Thread-1 1
ThreadName = Thread-1 2
ThreadName = Thread-1 3
ThreadName = Thread-1 4
ThreadName = Thread-1 5
ThreadName = Thread-3 1
ThreadName = Thread-3 2
ThreadName = Thread-3 3
ThreadName = Thread-3 4
ThreadName = Thread-3 5
ThreadName = Thread-4 1
ThreadName = Thread-4 2
ThreadName = Thread-4 3
ThreadName = Thread-4 4
ThreadName = Thread-4 5
从运行的结果来看,当前线程打印完毕之后将锁进行释放,其他线程才可以继续打印。线程打印的数据是分组打印,因为当前线程已经持有锁,但线程之间打印的顺序是随机的。
2.使用ReentrantLock实现同步:测试二
创建项目4.1.2,类MyService.java代码如下:
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 class ThreadA extends Thread{
private MyService service;
public ThreadA(MyService service){
super();
this.service = service;
}
@Override
public void run() {
service.methodA();
}
}
public class ThreadAA extends Thread{
private MyService service;
public ThreadAA(MyService service){
super();
this.service = service;
}
@Override
public void run() {
service.methodA();
}
}
第二组线程类代码如下:
public class ThreadB extends Thread{
private MyService service;
public ThreadB(MyService service){
super();
this.service = service;
}
@Override
public void run() {
service.methodB();
}
}
public class ThreadBB extends Thread{
private MyService service;
public ThreadBB(MyService service){
super();
this.service = service;
}
@Override
public void run() {
service.methodB();
}
}
类Run.java代码如下:
public class Run {
public static void main(String[] args) throws InterruptedException{
MyService myService = new MyService();
ThreadA a = new ThreadA(myService);
a.setName("A");
a.start();
ThreadAA aa = new ThreadAA(myService);
aa.setName("AA");
aa.start();
Thread.sleep(100);
ThreadB b = new ThreadB(myService);
b.setName("B");
b.start();
ThreadBB bb = new ThreadBB(myService);
bb.setName("BB");
bb.start();
}
}
运行结果如下所示:
methodA begin ThreadName = A time = 1660564373009
methodA end ThreadName = A time = 1660564378016
methodA begin ThreadName = AA time = 1660564378016
methodA end ThreadName = AA time = 1660564383029
methodB begin ThreadName = B time = 1660564383029
methodB end ThreadName = B time = 1660564388034
methodB begin ThreadName = BB time = 1660564388034
methodB end ThreadName = BB time = 1660564393047
由此可得:调用lock.lock代码的线程就持有了”对象监视器“,其它线程只有等待锁被释放时再次争抢。效果和使用synchronized关键字一样,线程之间还是顺序执行的。
3.使用Condition实现等待/通知:错误用法与解决
关键字synchronized与wait()和notify()、notifyAll()方法相结合可以实现等待/通知模式,类ReetrantLock也可以实现同样的功能,但需要借助于Condition对象。Condition类是在JDK5中出现的技术,使用它有更好的灵活性,使用它有更好的灵活性,比如可以实现多路通知功能,也就是在一个Lock对象里面可以创建多个Condition(即对象监控器)示例,线程对象可以注册在指定的Condition中,从而可以有选择性地进行通知,在调度线程上更加灵活。
在使用notify/notifyAll方法进行通知时,被通知的线程却是由JVM随机选择的。但使用ReentrantLock结合Condition类是可以实现前面介绍的”选择性通知“,这个功能是非常重要的,而且在Condition类中是默认提供的。
而synchronized就相当于整个Lock对象中只有一个单一的Condition对象,所有的线程都注册在它一个对象的身上。线程开始notifyAll时,需要通知所有的等待线程,没有选择权,会出现相当大的效率问题。
创建java项目4.1.3,类MyService.java代码如下:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class MyService {
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void await(){
try{
condition.await();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
ThreadA.java代码如下:
public class ThreadA extends Thread{
private MyService service;
public ThreadA(MyService service){
this.service = service;
}
@Override
public void run() {
service.await();
}
}
类Run.java代码如下:
public class Run {
public static void main(String[] args) {
MyService service = new MyService();
ThreadA a = new ThreadA(service);
a.start();
}
}
程序运行结果如下所示:
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.ReentrantLock$Sync.tryRelease(ReentrantLock.java:155)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1260)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.fullyRelease(AbstractQueuedSynchronizer.java:1723)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2040)
at MyService.await(MyService.java:14)
at ThreadA.run(ThreadA.java:9)
出现异常情况(无监视器对象)
报错的异常信息是监视器出错,解决的办法是必须在Condition.await方法调用之前调用lock.lock()代码获得同步监视器。
修改MyService.java代码如下:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class MyService {
private ReentrantLock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void await(){
try{
lock.lock();
System.out.println(
"A"
);
condition.await();
System.out.println("B");
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
程序运行结果如下所示:
A
在控制台只打印了A,原因是调用了Condition对象的await()方法,使当前执行任务的使线程进入等待WAITING状态。