Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing an object between two threads and main program

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.

like image 321
softwarematter Avatar asked Aug 31 '10 01:08

softwarematter


2 Answers

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;
 }

}
like image 158
Mike Avatar answered Oct 06 '22 11:10

Mike


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 0s in the print out. If you uncomment the synchronized block, the code will run without error.

like image 31
jjnguy Avatar answered Oct 06 '22 09:10

jjnguy