2.哥德巴赫猜想是任何不小于4的偶数,都可以写出两个质数之和的形式。它是世界三大数学难题之一,至今没有被完全证明。编写一个多线程程序验证100000000以内哥德巴赫猜想是对的。
java多线程实现:
class Source{private int num = 4;private boolean flag = true;private static int res[]=new int[100000001];private static boolean True=false;public boolean get(){return Source.True;}public static void create(){res[0]=res[1]=1;for(int i=2;i<100000001;i++){if(res[i]==0){int cnt=2;while(cnt*i<100000001){res[cnt*i]=1;cnt++;}}}}public synchronized void add() throws Exception {if(this.flag == false) {super.wait();}Thread.sleep(50);this.num+=2;int i;for(i=num-1;i>=num/2;i-=2){if(Source.res[i]==0&&Source.res[this.num-i]==0){
// System.out.println("当前执行线程:"+Thread.currentThread().getName()+" i = "+i+" j = "+(this.num-i)+"当前num = "+this.num);break;}}if(i<num/2){Source.True=true;}this.flag = true;super.notifyAll();}
}class AddThreads implements Runnable{private Source source;public AddThreads(Source source) {this.source = source;Source.create();}@Overridepublic void run() {for(int x=0;x<12500000;x++) {//(100000000-4)/2/4~12500000try {this.source.add();}catch(Exception e) {e.printStackTrace();}}}if(source.get()){System.out.println("猜想错误");}else{System.out.println("猜想正确");}
}public class Multipro {public static void main(String[] args) {Source source = new Source();AddThreads at = new AddThreads(source);new Thread(at, "A").start();new Thread(at, "B").start();new Thread(at, "C").start();new Thread(at, "D").start();}
}
如果正确应该得到四个猜想正确:因为每个线程都只是执行一部分。
考虑到时间:这里只执行了一部分

本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
