0
В примере кода сказано, что повторная синхронизация потоков основана на передаче сигналов с использованием семафора с задолженностью.Java - Что такое семафор с задолженностью
final Semaphore indebtedSemaphore = new Semaphore(1 - PROCESSOR_COUNT);
Какова цель этого негативного семафора, с моим ноутбуком он будет инициализирован -3
/**
* Sums two vectors, distributing the work load into as many new child threads as there
* are processor cores within a given system. Note that the added cost of thread
* construction and destruction is higher than the gain of distributing the work for
* practically any vector size.
* @param leftOperand the first operand
* @param rightOperand the second operand
* @return the resulting vector
* @throws NullPointerException if one of the given parameters is null
* @throws IllegalArgumentException if the given parameters do not share the same length
*/
public static double[] add(final double[] leftOperand, final double[] rightOperand) {
if (leftOperand.length != rightOperand.length) throw new IllegalArgumentException();
final double[] result = new double[leftOperand.length];
final int sectorWidth = leftOperand.length/PROCESSOR_COUNT;
final int sectorThreshold = leftOperand.length % PROCESSOR_COUNT;
final Semaphore indebtedSemaphore = new Semaphore(1 - PROCESSOR_COUNT);
for (int threadIndex = 0; threadIndex < PROCESSOR_COUNT; ++threadIndex) {
final int startIndex = threadIndex * sectorWidth + (threadIndex < sectorThreshold ? threadIndex : sectorThreshold);
final int stopIndex = startIndex + sectorWidth + (threadIndex < sectorThreshold ? 1 : 0);
final Runnable runnable = new Runnable() {
public void run() {
try {
for (int index = startIndex; index < stopIndex; ++index) {
result[index] = leftOperand[index] + rightOperand[index];
}
} finally {
indebtedSemaphore.release();
}
}
};
// EXECUTOR_SERVICE.execute(runnable); // uncomment for managed thread alternative!
new Thread(runnable).start(); // comment for managed thread alternative!
}
indebtedSemaphore.acquireUninterruptibly();
return result;
}
Я предполагаю, что это было только разработчик, признающий, что семафор начнется с возможными отрицательными значениями? Не уверен, хотя. –
Отрицательный семафор означает, что существует отрицательное количество доступных ресурсов. Другими словами, в этот момент приложение удерживает все ресурсы и должно освободить их, прежде чем какое-либо другое подразделение сможет их приобрести. http://stackoverflow.com/questions/1221322/how-does-semaphore-work –
@SotiriosDelimanolis, почему -3? – user1477955