开发者

Sharing an object between two threads and main program

开发者 https://www.devze.com 2023-01-14 17:26 出处:网络
I am new to Java and I\'m attending a Concurrent Programming course. I am desperately trying to get a minimal working example th开发者_如何学编程at can help to demonstrate concepts I have learnt like

I am new to Java and I'm attending a Concurrent Programming course. I am desperately trying to get a minimal working example th开发者_如何学编程at 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 0s in the print out. If you uncomment the synchronized block, the code will run without error.

0

精彩评论

暂无评论...
验证码 换一张
取 消