【发布时间】:2015-11-26 15:30:26
【问题描述】:
我正在尝试创建以下程序的多线程程序来计算 Pi。我的简单程序是:
import java.util.Random;
public class MonteCarloPi {
static Random generator = new Random( System.currentTimeMillis() );
/**
* @param args
*/
public static void main(String[] args) {
long N = 10000000;
if ( args.length > 1 )
N = Long.parseLong( args[0] );
double PI = myPiCompute(N);
System.out.println( N + " random samples yield an approximation of Pi = " + PI);
}
public static double myPiCompute (long N){
long Nc = 0;
for ( long i=0; i<N; i++ ) {
float x = generator.nextFloat()*2 - 1; // random float in [-1,1]
float y = generator.nextFloat()*2 - 1; // random float in [-1,1]
if ( x*x + y*y <= 1.0f )
Nc += 1;
}
double PI = 4.0*Nc/N;
return PI;
}
}
现在,我正在尝试使其成为多线程(至少 3 个线程)。所以我正在执行以下操作但遇到错误。
import java.util.Random;
class MyThread implements Runnable {
/**
* @param args
*/
static Random generator = new Random( System.currentTimeMillis() );
public void run() {
System.out.println("this thread is running ... ");
long N = 10000000;
if ( args.length > 1 )
N = Long.parseLong( args[0] );
double PI = myPiCompute(N);
System.out.println( N + " random samples yield an approximation of Pi = " + PI);
}
}
public static double myPiCompute (long N){
long Nc = 0;
for ( long i=0; i<N; i++ ) {
float x = generator.nextFloat()*2 - 1; // random float in [-1,1]
float y = generator.nextFloat()*2 - 1; // random float in [-1,1]
if ( x*x + y*y <= 1.0f )
Nc += 1;
}
double PI = 4.0*Nc/N;
return PI;
}
public class MonteCarloPi {
public static void main(String[] args) {
MyThread myObject = new MyThread();
Thread thr1 = new Thread(myObject);
thr1.start();
Thread thr2 = new Thread(myObject);
thr2.start();
Thread thr3 = new Thread(myObject);
thr3.start();
}
}
我收到以下错误。
MonteCarloPiPar.java:19: error: class, interface, or enum expected
public static double myPiCompute (long N){
^
MonteCarloPiPar.java:21: error: class, interface, or enum expected
for ( long i=0; i<N; i++ ) {
^
MonteCarloPiPar.java:21: error: class, interface, or enum expected
for ( long i=0; i<N; i++ ) {
^
MonteCarloPiPar.java:21: error: class, interface, or enum expected
for ( long i=0; i<N; i++ ) {
^
MonteCarloPiPar.java:23: error: class, interface, or enum expected
float y = generator.nextFloat()*2 - 1; // random float in [-1,1]
^
MonteCarloPiPar.java:24: error: class, interface, or enum expected
if ( x*x + y*y <= 1.0f )
^
MonteCarloPiPar.java:26: error: class, interface, or enum expected
}
^
MonteCarloPiPar.java:29: error: class, interface, or enum expected
return PI;
^
MonteCarloPiPar.java:30: error: class, interface, or enum expected
}
^
9 errors
我正在尝试使用多线程进行游戏。谁能指出我做错了什么。
【问题讨论】:
-
"I am getting many errors."-- 为什么不向我们展示错误?还有导致它们的线条?这似乎是合乎逻辑的事情,不是吗? -
首先,计算你的大括号,并确保所有左大括号与右大括号匹配。
-
在错误抛出行上方有一个额外的右大括号。
-
投票结束为错字。
-
同意@SotiriosDelimanolis——这只是一个粗心的错误。
标签: java multithreading