一、使用ReentrantLock类
public class MyService {
public 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();
}
}
public class MyThread extends Thread {
private MyService myService;
public MyThread(MyService myService) {
super();
this.myService = myService;
}
@Override
public void run() {
myService.testMethod();
}
}
public class TestThread {
public static void main(String[] args) {
MyService myService = new MyService();
MyThread thread1 = new MyThread(myService);
MyThread thread2 = new MyThread(myService);
MyThread thread3 = new MyThread(myService);
MyThread thread4 = new MyThread(myService);
MyThread thread5 = new MyThread(myService);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
}
从上述代码可以看出,调用lock.lock()方法的线程就持有了对象监视器,其他线程只有等待锁被释放时再次争抢。