java - 同步变量应该是什么?
问题描述
我正在创建一个估计 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();
}
解决方案
推荐阅读
- javascript - 在尝试了这个例子之后,对 JavaScript 中的 Maps 和 Set 的基础感到困惑
- typescript - 如何设置订阅状态是否已完成或错误的常见行为?
- mongodb - MongoDB 使用聚合执行连接
- python - 在 SpaCy 的优化器中更改默认学习率
- spring-cloud - 如何使用 URL->responsible-backend-service 映射服务动态路由传入请求?
- r - 如何使用 3 个输入变量在 R 中绘制线性判别分析图的决策边界
- linux - 随机读/写一个大文件-每次读/写时都使用mmap?
- scala - 如何在运行时为 docker 容器提供端口号?
- office365 - 在office365中调用create user时一个或多个属性包含无效值
- powerbi - X 轴表示同一图表中最近日期的年份和月份年份