- synchronize是关键字,属于JVM层面;ReentrantLock是具体的类,是API层面的锁
- synchronize不需要用户手动释放;ReentrantLock需要手动释放
- synchronize不可以被中断;ReentrantLock可以被中断
- synchronize是非公平锁;ReentrantLock 默认非公平锁,构建函数传入boolean值,true为公平锁,false为非公平锁。
- synchronize要么随机唤醒一个要么全部唤醒;ReentrantLock 用来实现需要分组唤醒需要唤醒的线程们,可以精确唤醒。
condition实现精确唤醒:
public class SynAndReetrantLockDemo {
static class ShareResource{
private int number = 1; //A=1;B=2;C=3
private Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();
public void print5() {
try {
lock.lock();
//1.判断
while (number != 1) {
condition1.await();
}
//2.干活
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + i);
Thread.sleep(200);
}
//3.通知
number = 2;
condition2.signal();
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void print10() {
try {
lock.lock();
//1.判断
while (number != 2) {
condition2.await();
}
//2.干活
for (int i = 1; i <= 10; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + i);
Thread.sleep(200);
}
//3.通知
number = 3;
condition3.signal();
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void print15() {
try {
lock.lock();
//1.判断
while (number != 3) {
condition3.await();
}
//2.干活
for (int i = 1; i <= 15; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + i);
Thread.sleep(200);
}
//3.通知
number = 1;
condition1.signal();
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
public static void main(String[] args) {
ShareResource shareResource = new ShareResource();
new Thread(()->{
for (int i = 1; i <= 10; i++) {
shareResource.print5();
}
},"A").start();
new Thread(()->{
for (int i = 1; i <= 10; i++) {
shareResource.print10();
}
},"B").start();
new Thread(()->{
for (int i = 1; i <= 10; i++) {
shareResource.print15();
}
},"C").start();
}
}
网友评论