java线程Lock的wait

如果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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值