✅ Перевірена відповідь на це питання доступна нижче. Наші рішення, перевірені спільнотою, допомагають краще зрозуміти матеріал.
Two threads are implemented to run respectively methodA() and methodB() in order to decrement/increment counter1 and counter2:
...private static Integer counter1=0; private static Integer counter2=0;Thread threadA = new Thread (()->methodA());Thread threadB = new Thread (()->methodB()); threadA.start();threadB.start();...
Which of the following implementations of the methods methodA() and methodB() may lead to a deadlock?
a)
public static void methodA() { for (int i=1; i<5; i++) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } counter1--; counter2++; } } public static void methodB() { for (int i=1; i<5; i++) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } counter1++; counter2--; } }
b)
private static void methodA() { for (int i=1; i<5; i++) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (counter1){ counter1--; } synchronized (counter2){ counter2++; } } } public static void methodB() { for (int i=1; i<5; i++) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (counter2) { counter2--; } synchronized (counter1) { counter1++; } } }
c)
public static void methodA() { for (int i=1; i<5; i++) { synchronized (counter2) { counter2--; try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (counter1) { counter1++; } } } } public static void methodB() { for (int i=1; i<5; i++) { synchronized (counter1) { counter1--; try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (counter2) { counter2++; } } } }
d)
public static void methodA() { for (int i=1; i<5; i++) { synchronized (counter1) { counter1--; try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void methodB() { for (int i=1; i<5; i++) { synchronized (counter1) { counter1++; try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } }
Отримайте необмежений доступ до відповідей на екзаменаційні питання - встановіть розширення Crowdly зараз!