如图下代码所示,在使用 lombda 为 Runnable 提供实现方法时,想要用 wait 释放线程资源,结果报错了,lombda中有办法使用 wait 这种方法吗。不行的话 在lombda 中又如何释放线程资源呢。
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class DemoMain {
public static void main(String[] args) {
DemoMain demo = new DemoMain();
demo.market();
}
public void market(){
AtomicInteger bread = new AtomicInteger(0);
Lock lock = new ReentrantLock();
Runnable product = () -> {
while (true) {
try {
lock.lock();
if (bread.get() < 99) {
bread.getAndIncrement();
}else{
this.wait();
}
System.out.println("生产者生产后,还有 " + bread.get() + " 个面包");
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
};
Runnable consumer = () -> {
while (true) {
try {
lock.lock();
if (bread.get() >= 1) {
bread.addAndGet(-1);
}else{
}
System.out.println("消费者消费后,还有 " + bread.get() + " 个面包");
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
};
new Thread(product).start();
new Thread(consumer).start();
}
}
<pre>
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock;
public class DemoMain {
public static void main(String[] args) {
DemoMain demo = new DemoMain();
demo.market();
}
public void market(){
AtomicInteger bread = new AtomicInteger(0);
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
Runnable product = () -> {
while (true) {
try {
lock.lock();
if (bread.get() < 99) {
bread.getAndIncrement();
}else{
condition.await();
}
System.out.println("生产者生产后,还有 " + bread.get() + " 个面包");
} catch (Exception e) {
e.printStackTrace();
} finally {
condition.signal();
lock.unlock();
}
}
};
Runnable consumer = () -> {
while (true) {
try {
lock.lock();
if (bread.get() >= 1) {
bread.addAndGet(-1);
}else{
condition.await();
}
System.out.println("消费者消费后,还有 " + bread.get() + " 个面包");
} catch (Exception e) {
e.printStackTrace();
} finally {
condition.signal();
lock.unlock();
}
}
};
new Thread(product).start();
new Thread(consumer).start();
}
}
https://blog.csdn.net/wd_888/article/details/105154184
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。