await 方法
public class MyService {
private Lock lock = new ReentrantLock();
private Condition condition=lock.newCondition();
public void testMethod() {
try {
lock.lock();
System.out.println("开始 wait");
condition.await();
for (int i = 0; i < 5; i++) {
System.out.println("ThreadName=" +
Thread.currentThread().getName()
+ (" " + (i + 1)));
}
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
finally
{
lock.unlock();
}
}
}
通过创建 Condition 对象来使线程 wait,必须先执行 lock.lock 方法获得锁
评论0
最新资源