Java 在两个线程和主程序之间共享一个对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3605476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sharing an object between two threads and main program
提问by devnull
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.
我是 Java 新手,正在参加并发编程课程。我拼命地试图获得一个最小的工作示例,它可以帮助演示我学到的概念,例如使用“同步”关键字和跨线程共享对象。一直在寻找,但是没有得到一个基本的框架。Java程序员,请帮助。
采纳答案by jjnguy
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.
但是,如果您arr
在循环周围同步,您将始终0
在打印输出中看到所有s。如果取消对同步块的注释,代码将运行而不会出错。
回答by Mike
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;
}
}