为什么java类中可以创建实例_Java中静态类为什么也可以实例化
发布日期:2021-06-24 13:33:52 浏览次数:2 分类:技术文章

本文共 1760 字,大约阅读时间需要 5 分钟。

这是我在书中看到的代码,代码中有把实例化静态内部类。静态类怎么可以实例化?为什么要这么做?

import java.util.concurrent.*;

import java.util.concurrent.locks.*;

public class Consumerproducer {

private static Buffer buffer = new Buffer();

public static void main(String[] args) {

ExecutorService executor = Executors.newFixedThreadPool(2);

executor.execute(new Producertask());

executor.execute(new ConsumerTask());

}

static class Producertask implements Runnable {

public void run() {

int i = 10;

try {

while (true) {

System.out.println("Producer writes " + i);

buffer.write(i++);

Thread.sleep((int) (Math.random() * 10000));

}

} catch (InterruptedException ex) {

ex.printStackTrace();

}

}

}

static class ConsumerTask implements Runnable {

public void run() {

try {

while (true) {

System.out.println("\t\tConsumer reads " + buffer.read());

Thread.sleep((int) (Math.random() * 10000));

}

} catch (InterruptedException ex) {

ex.printStackTrace();

}

}

}

private static class Buffer {

private static final int CAPACITY = 1;

private java.util.LinkedList queue =

new java.util.LinkedList<>();

private static Lock lock = new ReentrantLock();

private static Condition notEmpty = lock.newCondition();

private static Condition notFull = lock.newCondition();

public void write(int value) {

lock.lock();

try {

while (queue.size() == CAPACITY) {

System.out.println("Wait for notFull condition");

notFull.await();

}

queue.offer(value);

notEmpty.signal();

} catch (InterruptedException ex) {

ex.printStackTrace();

}

}

public Integer read() {

int value = 0;

lock.lock();

try {

while (queue.isEmpty()) {

System.out.println("Wait for notEmpty condition");

notEmpty.await();

}

value=queue.remove();

notFull.signalAll();

} catch (InterruptedException ex) {

ex.printStackTrace();

} finally {

lock.unlock();

return value;

}

}

}

}

转载地址:https://blog.csdn.net/weixin_33212263/article/details/114810563 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:java 身边距离怎么查询_附近的人位置距离计算方法
下一篇:java画bezier曲线_OpenGL画bezier曲线

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年04月04日 13时42分39秒