学习ReentrantLock
1. 使用ReentrantLock
import java.util.concurrent.locks.ReentrantLock; public class TestReentrantLock { public static void main(String[] args) { final ReentrantLock reentrantLock = new ReentrantLock(true); reentrantLock.lock(); new Thread("Thread 1") { public void run() { for (int i = 1; i < 5; i++) { reentrantLock.lock(); System.out.println(Thread.currentThread().getName() + " print " + i); reentrantLock.unlock(); } } }.start(); new Thread("Thread 2") { public void run() { for (int i = 1; i < 5; i++) { reentrantLock.lock(); System.out.println(Thread.currentThread().getName() + " print " + i); reentrantLock.unlock(); } } }.start(); System.out.println(Thread.currentThread().getName() + " Done"); reentrantLock.unlock(); } }
结果为:
main Done Thread 1 print 1 Thread 1 print 2 Thread 1 print 3 Thread 1 print 4 Thread 2 print 1 Thread 2 print 2 Thread 2 print 3 Thread 2 print 4