如何解决同步变量应该是什么?
我正在创建一个估计 Pi 的 Monte Carlo 线程系统,我需要使整个 go 方法或 run 方法原子化,我应该将哪个方法原子化,如果是 run 方法,我应该使用什么变量传入synchronized方法?
public class PiThreads {
public static double N;
public static double T;
private ArrayList<Thread> threads;
public double piEstimate;
public static void main(String[] args) {
if(args.length != 2){
System.err.println("usage java PiThreads threads iterations");
System.exit(1);
}
else if(Integer.parseInt(args[0]) < 0 || Integer.parseInt(args[0]) > 1000){
System.err.println(" Threads needs to be greater than 0 and less than or equal to 1000");
System.exit(1);
}
else if(Integer.parseInt(args[1]) < 0 || Integer.parseInt(args[1]) > 10000 ){
System.err.println("Iterations need to be greater than 0 and less than or equal to 100000");
System.exit(1);
}
T = Integer.parseInt(args[0]);
N = Integer.parseInt(args[1]);
(new PiThreads()).go();
}
private void go(){
threads = new ArrayList<Thread>();
double x = Math.random();
double y = Math.random();
for(int i =0; i < T; i++){
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
synchronized() { //Atomic code
int hits = 0;
int misses = 0;
double original = Math.sqrt(x * x + y * y);
if (original <= 1) {
hits++;
}
misses++;
piEstimate = (4.0 * hits) / misses;
}
}
});
threads.add(thread);
thread.start();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。