java編程之多線程計算

/*
 *編寫兩個線程: 
 *第一個線程計算2-1000000之間的質數及個數 
 *第二個線程計算1000000-2000000之間的質數 及個數 
 */

class myThread extends Thread{
	private int a,b;  //變量的聲明
	private int count;  
	private int count1=0;
	
	myThread(int x,int y){  //賦值函數
	    a=x;
		b=y;
	}
	
	public void run(){  //線程執行任務
		try{
			for(int i=a;i<=b;i++){  //for循環,計算a,b之間質數
				count=1;  //因數個數變量
				for(int j=2;j<=i;j++){  //for循環,計算因數個數
					if(i%j==0){  //如果i整除j,則j是i的因數
						count++;  //因數計數器+1
					}
					if(count>2){  //如果因數個數大於2 
						break;  //跳出磁層循環
					}
				}
				
				if(count==2){  //如果該數只有兩個因數,說明這個數是質數
						System.out.print(i+" ");  //輸出質數
						count1++;  //質數個數計數器+1
					}
			}
			
			System.out.println(a+"和"+b+"之間有"+count1+"個質數");
		}catch(Exception e)  //捕捉異常
		{return;}
	}
}

public class prime{
	public static void main(String args[]){  
		myThread ta=new myThread(2,1000000);  //類對象
	    myThread tb=new myThread(1000000,2000000);
	    
	    ta.start();  //多線程的運行
	    tb.start();
	}
	
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章