Многопоточность Java - блок if
Всем привет, вопрос такой, можно ли избавиться от блока if в данном случае, чтоб выводило с такими же таймингами?
public class AffableThread extends Thread {
private final Object object;
AffableThread(String name, Object object) {
this.setName(name);
this.object = object;
}
@Override
public void run() {
synchronized (object) {
while (true) {
System.out.println(getName());
try {
if(getName().equals("Понг")) {
Thread.sleep(5000);
} else {
Thread.sleep(1000);
}
} catch (InterruptedException interruptedException) {
}
object.notify();
try {
object.wait();
} catch (InterruptedException e) {}
}
}
}
}
Main
public class Main {
public static void main(String[] args) {
Object object = new Object();
AffableThread thread1 = new AffableThread("Пинг", object);
AffableThread thread2 = new AffableThread("Понг", object);
thread1.start();
thread2.start();
}
}
Ответы (1 шт):
Автор решения: Aziz Umarov
→ Ссылка
Избавится можно разными способами.
Я предложу такой.
public class AffableThread extends Thread {
private final Object object;
private long delay;
AffableThread(String name, Object object) {
this.setName(name);
this.object = object;
this.delay = name.equals("Понг") ? 5000 : 1000;
}
@Override
public void run() {
synchronized (object) {
while (true) {
System.out.println(getName());
try {
Thread.sleep(this.delay);
} catch (InterruptedException interruptedException) {
}
object.notify();
try {
object.wait();
} catch (InterruptedException e) {}
}
}
}
}