private void reclaimPrinter(Printer p) {
lock.lock();
this.freePrinters[p.getIndex()] = true;
lock.unlock();
}
}
最后编写测试代码,启动10个线程请求使用打印机:
// create printer pool
PrinterPool pool = new PrinterPool();
Runnable job = () -> {
pool.printData();
};
// create 10 threads
Thread[] threads = new Thread[10];
for (int ix = 0 ; ix < 10 ; ++ix) {
threads[ix] = new Thread(job);
}
// start all threads
for (int ix = 0 ; ix < 10 ; ++ix) {
threads[ix].start();
}
输出结果: