您的位置:首页 > 编程语言 > Java开发

【并行计算作业】java多线程技术求1000000以内的素数

2013-11-18 10:25 323 查看
CountDownLatch

package jingtianxiaozhi;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountdownLatchTest {

public static int num;
public static void main(String[] args) {
long start =System.currentTimeMillis();
ExecutorService service = Executors.newCachedThreadPool();
final CountDownLatch cdAnswer = new CountDownLatch(2);
Runnable runnable1 = new Runnable(){
public void run(){
try {
for(int i=3;i<=1000000;i+=2)
{
boolean mark=true;
for(int j=2;j<=Math.sqrt(i);j++)
{
if(i%j==0)
{
mark=false;
break;
}
}
if(mark)
synchronized (Thread.class) {
num++;
}
}
cdAnswer.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}
};
Runnable runnable2 = new Runnable(){
public void run(){
try {
for(int i=2;i<=1000000;i+=2)
{
boolean mark=true;
for(int j=2;j<=Math.sqrt(i);j++)
{
if(i%j==0)
{
mark=false;
break;
}
}
if(mark)
synchronized (Thread.class) {
num++;
}
}
cdAnswer.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}
};
service.execute(runnable1);
service.execute(runnable2);

try {
cdAnswer.await();
System.out.println("1000000以内求得的素数个数是:"+num);
long end =System.currentTimeMillis();
System.out.println("并行计算所用时间:"+(end-start)+"毫秒");
} catch (Exception e) {
e.printStackTrace();
}
service.shutdown();

}
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: