#java #многопоточность
Задача - написать семафор без util.concurrent.*, только wait/notify/notifyAll
Сам семафор:
public class MySemaphore {
private int permits;
public MySemaphore(int permits) {
this.permits = permits;
}
public synchronized void acquire() throws InterruptedException {
if (permits > 0) {
permits--;
}
else {
this.wait();
permits--;
}
}
public synchronized void release() {
permits++;
if (permits > 0) {
this.notify();
}
}
public boolean tryAcquire() {
if (permits > 0) {
return true;
}
return false;
}
}
Два типа потоков для проверки:
1) Инкрементный
public class IncrementThread implements Runnable {
MySemaphore semaphore;
String name;
int count;
public String getName() {
return name;
}
public IncrementThread(MySemaphore semaphore, String name, int count) {
this.semaphore = semaphore;
this.name = name;
this.count = count;
System.out.println(name + " was created");
}
@Override
public synchronized void run() {
System.out.println(Thread.currentThread().getName() + " is waiting for permit");
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + " is got for permit");
for (int i=0; i
Ответы
Ответ 1
Результат одновременно "выстреливают" не потоки, а логи этих потоков. Сами потоки
работают как положено с задержкой в 2 секунды.
Добавьте два synchronized метода incrementCount и decrementCount, и работайте с ними
вместо переменной напрямую..
public class SharedValue {
private static volatile int count = 0;
public static int getCount() {
return count;
}
public static synchronized void incrementCount() {
count++;
}
public static synchronized void decrementCount() {
count--;
}
}
Комментариев нет:
Отправить комментарий