在Java多线程中,可以使用synchronized关键字来实现线程之间同步互斥,但在JDK1.5中新增了ReentrantLock类也能达到同样的效果,并且在扩展功能上也更加强大,比如具有嗅探锁定、多路分支通知等功能,而且在使用上也比synchronized更加的灵活。
调用ReentrantLock对象的lock方法获取锁,调用unlock方法释放锁。
package org.github.lujiango;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test05 {
static class Service {
private Lock lock = new ReentrantLock();
public void testMethod() {
try {
lock.lock();
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " " + (i + 1));
}
} finally {
lock.unlock();
}
}
}
static class MyThread extends Thread {
private Service service;
public MyThread(Service service) {
this.service = service;
}
@Override
public void run() {
service.testMethod();
}
}
public static void main(String[] args) {
Service service = new Service();
MyThread t1 = new MyThread(service);
MyThread t2 = new MyThread(service);
MyThread t3 = new MyThread(service);
MyThread t4 = new MyThread(service);
MyThread t5 = new MyThread(service);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
当前线程打印完毕之后将锁进行释放,其它线程才可以继续打印。线程打印的数据是分组打印的,因为当前线程已经持有锁,但线程之间打印的顺序是随机的。