如果lock在lock.lock();之后进入lock.wait();
那么所有的获取lock.lock();的代码都会被阻塞。
但是synchronized (lock) { lock.notifyAll(); } 这个代码可以被执行,且只有执行唤醒之后才能使得程序继续走。
看代码
class R1 implements Runnable {
public void run() {
try {
lock.lock();
System.out.println("r1-01\t" + Thread.currentThread().getName());
System.out.println("进入等待");
synchronized (lock) {
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
System.out.println("over");
}
}
class R2 implements Runnable {
public void run() {
lock.lock();
System.out.println("r2-01\t" + Thread.currentThread().getName());
sleep(10);
synchronized (lock) {
lock.notifyAll();
}
}
}
如果先运行R1在运行R2
就无法结束程序,
如果吧R2的获取锁的代码注释掉就可以
但是使用了lock最好使用private static Condition canGet = lock.newCondition();去等待和唤醒
代码如下
public class MyLock_1 {
private static Lock lock = new ReentrantLock();// 锁对象
private static Condition canGet = lock.newCondition();
public int n1 = 1;
public int n2 = 1;
public void task() {
Thread[] t1 = new Thread[n1];
for (int i = 0; i < n1; i++) {
R1 r = new R1();
t1[i] = new Thread(r, "R1999-" + i);
t1[i].start();
}
sleep(2);
Thread[] t2 = new Thread[n2];
for (int i = 0; i < n2; i++) {
R2 r = new R2();
t2[i] = new Thread(r, "R2000-" + i);
t2[i].start();
}
}
public static void main(String[] args) {
MyLock_1 lock = new MyLock_1();
lock.task();
}
class R1 implements Runnable {
public void run() {
lock.lock();
try {
System.out.println("r1-01\t" + Thread.currentThread().getName());
sleep(5);
System.out.println("进入等待");
canGet.await();
System.out.println("离开等待--");
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
lock.unlock();
}
System.out.println("over");
}
}
class R2 implements Runnable {
public void run() {
lock.lock();
System.out.println("r2-01\t" + Thread.currentThread().getName());
canGet.signal();
lock.unlock();
System.out.println("r2-01\tover");
}
}
public void sleep(int sec) {
try {
Thread.sleep(100 * sec);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
http://blog.csdn.net/ghsau/article/details/7481142