java实现减少cpu,什么可能导致java进程逐渐减少CPU的份额?

如果你想尝试平衡一切,你应该创建一个队列来保存要打印的数字,然后让一个线程生成它们(生产者),另一个线程读取并打印它们(消费者)。这可以通过LinkedBlockingQueue轻松完成。

public class PrintQueueExample {

private BlockingQueue printQueue = new LinkedBlockingQueue();

public static void main(String[] args) throws InterruptedException {

PrinterThread thread = new PrinterThread();

thread.start();

for (int i = 0; i < 1000000; i++) {

int toPrint = ...(i) ;

printQueue.put(Integer.valueOf(toPrint));

}

thread.interrupt();

thread.join();

System.out.println("Complete");

}

private static class PrinterThread extends Thread {

@Override

public void run() {

try {

while (true) {

Integer toPrint = printQueue.take();

System.out.println(toPrint);

}

} catch (InterruptedException e) {

// Interruption comes from main, means processing numbers has stopped

// Finish remaining numbers and stop thread

List remainingNumbers = new ArrayList();

printQueue.drainTo(remainingNumbers);

for (Integer toPrint : remainingNumbers)

System.out.println(toPrint);

}

}

}

}

此代码可能存在一些问题,但这是它的要点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值