【发布时间】:2015-06-21 20:42:32
【问题描述】:
所以我有这个生成 2 个随机步行者的多线程程序,每个步行者都是一个单独的线程,因为我需要它们同时移动。每个步行者随机向 4 个方向中的任何一个移动。第一个问题是我认为 stdDraw 不是线程安全的,因此在没有锁定我的整个函数的情况下,它往往会无缘无故地在随机点绘制随机方块,整个事情变得非常有问题。当我在我的函数周围加锁时,一个线程变得比另一个线程慢,因为它有时必须等待锁。所以这些威胁不再是同时发生的。有针对这个的解决方法吗?我遇到的另一个问题是我希望它在两个步行者相交时脱离循环,但由于某种原因,两个线程不知道另一个线程的位置。一个人认为另一个人的位置总是在(0,0)。谢谢!
import java.awt.Color;
public class WalkerThread implements Runnable {
String name;
static Integer lock = new Integer(1000);
int num;
static int steps = 0, steps2 = 0;
static int x = 0, y = 0;
static int x2 = -1, y2 = -2;
public WalkerThread(String s, int n) {
this.name = s;
this.num = n;
}
@Override
public void run() {
int N = 10;
StdDraw.create(600, 600);
StdDraw.setScale(-N, -N, +N, +N);
StdDraw.clear(Color.gray);
do {
synchronized (lock) {
if (num == 1) {
StdDraw.go(x, y);
StdDraw.setColor(Color.white);
StdDraw.spot(0.9, 0.9);
double r = Math.random();
if (r < 0.25)
x--;
else if (r < 0.50)
x++;
else if (r < 0.75)
y--;
else if (r < 1.00)
y++;
steps++;
StdDraw.setColor(Color.blue);
StdDraw.go(x, y);
StdDraw.spot(0.9, 0.9);
StdDraw.pause(40);
}
if (num == 2) {
StdDraw.go(x2, y2);
StdDraw.setColor(Color.yellow);
StdDraw.spot(0.9, 0.9);
double r2 = Math.random();
if (r2 < 0.25)
x2--;
else if (r2 < 0.50)
x2++;
else if (r2 < 0.75)
y2--;
else if (r2 < 1.00)
y2++;
steps2++;
StdDraw.setColor(Color.green);
StdDraw.go(x2, y2);
StdDraw.spot(0.9, 0.9);
StdDraw.pause(40);
}
}// lock
/*String pict = steps + ".png";
StdDraw.save(pict);*/
//if (posX == posX2 && posY == posY2) break;
} while ((Math.abs(x) < N && Math.abs(y) < N) && (Math.abs(x2) < N && Math.abs(y2) < N));
System.out.printf("Total steps of %s is %d and %d \n", name, steps, steps2);
}
}
//主要
public class Walkers{
public static void main(String[] args) {
Thread t1 = new Thread(new WalkerThread("one", 1));
Thread t2 = new Thread(new WalkerThread("two", 2));
t1.start();
t2.start();
}
}
【问题讨论】:
-
您的 StdDraw 类属于哪个库?还有,为什么要在当前的 WalkerThread 实例上同步
run()方法呢?这有什么用? -
如果你能提供整个代码会更容易。您的代码肯定需要更改。为了更好更准确地提供帮助,是否可以提供所有代码?
-
包括了我的 main (Walkers.java),以及前面评论中提到的两个库。就这样。让我知道你是否需要其他任何东西。
标签: java multithreading random thread-safety thread-synchronization