简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM