问题描述
因此,对于我大学里的一个问题,我们被要求为该Java程序实现Petersons解决方案,并且已经声明我们只能添加一些变量,而不能显着更改代码。我对此很陌生,并努力使自己步入正轨,并希望获得任何帮助。
public class SlowRaceTwo {
public static void main(String args []) throws Exception {
MyThread.count = 0 ;
MyThread thread1 = new MyThread() ;
thread1.name = "A" ;
MyThread thread2 = new MyThread() ;
thread2.name = "B" ;
thread1.start() ;
thread2.start() ;
thread2.join() ;
thread1.join() ;
System.out.println("MyThread.count = " + MyThread.count) ;
}
}
class MyThread extends Thread {
volatile static int count ;
String name ;
public void run() {
for(int i = 0 ; i < 10 ; i++) {
/* Critical section */
delay() ;
int x = count ;
System.out.println("Thread " + name + " read " + x);
delay() ;
count = x + 1 ;
System.out.println("Thread " + name + " wrote " + (x + 1)) ;
/* */
}
}
void delay() {
int delay = (int) (1000 * Math.random()) ;
try {
Thread.sleep(delay) ;
}
catch(Exception e) {
}
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)