Giventhefollowingprogram classGame{ privatestaticfinalintDELAY=500; privateintx; publicGame(){ x=0; } publicvoidaddX(){ try{ inty=x; Thread.sleep((int)(DELAY*Math.random())); y+=1; x=y; System.out.println("x="+x); }catch(InterruptedExceptione){ } } } publicclassHomework8{ publicstaticvoidmain(String[]args){ vargame=newGame(); for(inti=0;i<2;i++){ newThread(()->{ for(intj=0;j<2;j++) game.addX(); }).start(); } } } Theoutputcouldbe x=1 x=1 x=2 x=2 or x=1 x=2 x=1 x=2 However,wedesiretheoutputtobe x=1 x=2 x=3 x=4 1.ModifytheaddXmethodusing"synchronized"togetthedesiredoutput. Code:
时间: 2023-09-18 09:13:06 浏览: 89
To modify the `addX` method using `synchronized`, we can add the `synchronized` keyword to the method signature. This will ensure that only one thread can execute the method at a time, preventing the interleaving of the `x` variable updates.
Here's the modified code:
```java
class Game {
private static final int DELAY = 500;
private int x;
public Game() {
x = 0;
}
public synchronized void addX() {
try {
int y = x;
Thread.sleep((int) (DELAY * Math.random()));
y += 1;
x = y;
System.out.println("x=" + x);
} catch (InterruptedException e) {
}
}
}
public class Homework8 {
public static void main(String[] args) {
Game game = new Game();
for (int i = 0; i < 2; i++) {
new Thread(() -> {
for (int j = 0; j < 2; j++)
game.addX();
}).start();
}
}
}
```
With this modification, the output should always be `x=1 x=2 x=3 x=4`.
阅读全文