首页 > 解决方案 > 同步变量应该是什么?

问题描述

我正在创建一个估计 Pi 的 Monte Carlo 线程系统,我需要将整个 go 方法或 run 方法设为原子,我应该将哪一个设为原子,如果是 run 方法,我应该使用什么变量传入同步方法?

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();
        }
        

标签: javapi

解决方案


推荐阅读