I am new to Java and I'm attending a Concurrent Programming course. I am desperately trying to get a minimal working example that can help to demonstrate concepts I have learnt like using 'synchronized' keyword and sharing an object across threads. Have been searching, but could not get a basic framework. Java programmers, kindly help.
A simple example. Hope you like soccer (or football). :)
public class Game {
public static void main(String[] args) {
Ball gameBall = new Ball();
Runnable playerOne = new Player("Pasha", gameBall);
Runnable playerTwo = new Player("Maxi", gameBall);
new Thread(playerOne).start();
new Thread(playerTwo).start();
}
}
public class Player implements Runnable {
private final String name;
private final Ball ball;
public Player(String aName, Ball aBall) {
name = aName;
ball = aBall;
}
@Override
public void run() {
while(true) {
ball.kick(name);
}
}
}
public class Ball {
private String log;
public Ball() {
log = "";
}
//Removing the synchronized keyword will cause a race condition.
public synchronized void kick(String aPlayerName) {
log += aPlayerName + " ";
}
public String getLog() {
return log;
}
}
Here is a very shot example of sharing an array between two threads. Usually you will see all zeros, but sometimes things get screwy and you see other numbers.
final int[] arr = new int[100];
Thread one = new Thread() {
public void run() {
// synchronized (arr) {
for (int i = 0; i < arr.length * 100000; i++) {
arr[i % arr.length]--;
}
// }
}
};
Thread two = new Thread() {
public void run() {
// synchronized (arr) {
for (int i = 0; i < arr.length * 100000; i++) {
arr[i % arr.length]++;
}
//}
}
};
one.start();
two.start();
one.join();
two.join();
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
But, if you synchronize on arr
around the looping you will always see all 0
s in the print out. If you uncomment the synchronized block, the code will run without error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With