欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入
//随机产生一个在正方形区域的点,判断它是否在圆中
public boolean isInCircle(){
double x=Math.random();
double y=Math.random();
if((x-0.5)*(x-0.5)+(y-0.5)*(y-0.5)<0.25)
return true;
else
return false;
}
public static int getTotal(){
return M;
}
}
多线程Main实现
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MutliThread {
public static void main(String[] args) throws InterruptedException {
long begin=System.currentTimeMillis();
int threadSize=100;
int N=1000000;
OBJ semaphore = new OBJ();
CountDownLatch doneSignal = new CountDownLatch(threadSize);
ProModel[] pros=new ProModel[threadSize];
//设置特定的线程池,大小为threadSizde
System.out.println(“begins!”);
ExecutorService exe = Executors.newFixedThreadPool(threadSize);
for(int i=0;i<threadSize;i++)
exe.execute(new ProModel(i+1,doneSignal,N,semaphore));
try{
doneSignal.await(); //等待end状态变为0, }catch (InterruptedException e) {
// TODO: handle exception35
e.printStackTrace();
}finally{
System.out.println(“ends!”);
System.out.println(4*(float)ProModel.getTotal()/(float)(threadSize*N));
}
exe.shutdown();
long end=System.currentTimeMillis();
System.out.println(“used time(ms):”+(end-begin));
}
}
class OBJ{}
单线程Main实现
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SingleThread {
public static void main(String[] args) {
long begin=System.currentTimeMillis();
int threadSize=1;
int N=100000000;
OBJ semaphore = new OBJ();
CountDownLatch doneSignal = new CountDownLatch(threadSize);
ProModel[] pros=new ProModel[threadSize];
//设置特定的线程池,大小为5
System.out.println(“begins!”);
ExecutorService exe = Executors.newFixedThreadPool(threadSize);
for(int i=0;i<threadSize;i++)
exe.execute(new ProModel(i+1,doneSignal,N,semaphore));
try{
doneSignal.await(); //等待end状态变为0, }catch (InterruptedException e) {
// TODO: handle exception35
e.printStackTrace();
}finally{
System.out.println(“ends!”);
System.out.println(4*(float)ProModel.getTotal()/(float)(threadSize*N));
}
exe.shutdown();
long end=System.currentTimeMillis();
System.out.println(“used time(ms):”+(end-begin));
}
}
运行结果比较
根据运行结果看,由于多线程运行时要进行分配资源的操作,在单机上的运行速度并没有单线程效率高.
[1][2]
美好的生命应该充满期待惊喜和感激