显式锁真好用╮( ̄▽ ̄")╭,以下是尚硅谷老师讲JUC时用的课件,我给粘过来了,说明一下Lock
- 在 Java 5.0 之前,协调共享对象的访问时可以使用的机制只有synchronized 和 volatile 。Java 5.0 后增加了一些新的机制,但并不是一种替代内置锁的方法,而是当内置锁不适用时,作为一种可选择的高级功能。
- ReentrantLock 实现了 Lock 接口,并提供了与synchronized 相同的互斥性和内存可见性。但相较于synchronized 提供了更高的处理锁的灵活性。
继续用这个做题吧。
package multithreading;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class MyFooBar {
public static void main(String[] args) {
FooBar fb = new FooBar(5); //为了测试简单,给定值5
new Thread(new Runnable() {
@Override
public void run() {
try {
fb.foo(new Runnable() {
@Override
public void run() {
System.out.println("foo");
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
fb.bar(new Runnable() {
@Override
public void run() {
System.out.println("bar");
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
class FooBar {
private int n;
private Lock lock = new ReentrantLock();
private int flag = 1;
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
public FooBar(int n) {
this.n = n;
}
public void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
lock.lock();
if(flag != 1) {
condition1.await();
}
// printFoo.run() outputs "foo". Do not change or remove this line.
printFoo.run();
flag = 2;
condition2.signal();
lock.unlock();
}
}
public void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
lock.lock();
if(flag != 2) {
condition2.await();
}
// printBar.run() outputs "bar". Do not change or remove this line.
printBar.run();
flag = 1;
condition1.signal();
lock.unlock();
}
}
}