java常见面试考点
往期文章推荐:
java常见面试考点(四十一):short运算小错误
java常见面试考点(四十二):序列化与反序列化
java常见面试考点(四十三):泛型
java常见面试考点(四十四):Comparable和Comparator接口
java常见面试考点(四十五):阻塞队列
【版权申明】未经博主同意,谢绝转载!(请尊重原创,博主保留追究权);
本博客的内容来自于:java常见面试考点(四十六):生产者消费者;
学习、合作与交流联系q384660495;
本博客的内容仅供学习与参考,并非营利;
一、Java能实现的几种方法
-
wait() / notify()方法
-
await() / signal()方法
-
BlockingQueue阻塞队列方法
-
信号量
-
管道
二、wait() / notify()方法
class ShareData{
private int number = 0;
public void increment() throws InterruptedException {
synchronized (this){
while(number != 0){
this.wait();
}
number++;
System.out.println("increment number = " + number);
this.notifyAll();
}
}
public void decrement() throws InterruptedException {
synchronized (this){
while(number == 0){
this.wait();
}
number--;
System.out.println("decrement number = " + number);
this.notifyAll();
}
}
}
三、await() / signal()方法
class ShareData{
private int number = 0;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void increment() throws InterruptedException {
lock.lock();
try {
while (number!=0){
System.out.println("ShareData.increment");
condition.await();
}
number++;
System.out.println("increment number = " + number);
condition.signalAll();
}finally {
lock.unlock();
}
}
public void decrement() throws InterruptedException {
lock.lock();
try {
while (number==0){
System.out.println("ShareData.decrement");
condition.await();
}
number--;
System.out.println("decrement number = " + number);
condition.signalAll();
}finally {
lock.unlock();
}
}
}
四、BlockingQueue阻塞队列方法
class MyResource{
private volatile boolean FLAG = true;
private AtomicInteger integer = new AtomicInteger();
BlockingQueue<String> blockingQueue = null;
public MyResource(BlockingQueue<String> blockingQueue){
this.blockingQueue = blockingQueue;
System.out.println("blockingQueue.getClass().getName() = " + blockingQueue.getClass().getName());
}
public void product() throws InterruptedException {
String data = null;
boolean flag;
while (FLAG){
data = integer.incrementAndGet() + "";
flag = blockingQueue.offer(data, 2L, TimeUnit.SECONDS);
if(flag){
System.out.println("生产线程启动: " + flag);
}else {
System.out.println("生产线程启动失败 " );
}
TimeUnit.SECONDS.sleep(1);
}
System.out.println("product over ");
}
public void consume() throws InterruptedException {
String data = null;
boolean flag;
while (FLAG){
data = integer.incrementAndGet() + "";
String poll = blockingQueue.poll(2L, TimeUnit.SECONDS);
System.out.println("消费线程取出: " + poll);
TimeUnit.SECONDS.sleep(1);
}
System.out.println("consume over ");
}
public void stop(){
this.FLAG = false;
}
}