一個進程就是在一個運行的程序
線程與進程相似
采用繼承Thread類創建線程
該方法比較簡單
通過實現Runnable接口創建線程
該方法通過生成實現java
public Thread(Runnable target);來實現
以使用蒙特卡羅概率算法求π為例
蒙特卡羅法(Monte Carlo method)是以概率和統計的理論
蒙特卡羅求算法求π
第一步
畫正方形和內切圓
第二步
變換表達式
正方形面積As=(
圓的面積Ac=πR^
Ac/As=(
π=
令P=As/Sc
第三步
重復N次實驗求平均值
在正方形區域內隨機生成一個點A
P=M/N
π=
N取值為
線程實現
import ncurrent
public class ProModel implements Runnable {
public int N;//隨機實驗的總次數
public static int M;//隨機點落在圓中的次數
private int id;
private final CountDownLatch doneSignal;
OBJ semaphore;
public ProModel(int id
this
this
this
this
M=
}
public void run(){
int tempM=
for(int i=
if(isInCircle()){
tempM++;
}
}
synchronized (semaphore) {
add(tempM);
}
untDown();//使end狀態減
}
public void add(int tempM){
System
M=M+tempM;
System
}
//隨機產生一個在正方形區域的點
public boolean isInCircle(){
double x=Math
double y=Math
if((x
return true;
else
return false;
}
public static int getTotal(){
return M;
}
}
多線程Main實現
import ncurrent
import ncurrent
import ncurrent
public class MutliThread {
public static void main(String[] args) throws InterruptedException {
long begin=System
int threadSize=
int N=
OBJ semaphore = new OBJ();
CountDownLatch doneSignal = new CountDownLatch(threadSize);
ProModel[] pros=new ProModel[threadSize];
//設置特定的線程池
System
ExecutorService exe = Executors
for(int i=
exe
try{
doneSignal
// TODO: handle exception
e
}finally{
System
System
}
exe
long end=System
System
}
}
class OBJ{}
單線程Main實現
import ncurrent
import ncurrent
import ncurrent
public class SingleThread {
public static void main(String[] args) {
long begin=System
int threadSize=
int N=
OBJ semaphore = new OBJ();
CountDownLatch doneSignal = new CountDownLatch(threadSize);
ProModel[] pros=new ProModel[threadSize];
//設置特定的線程池
System
ExecutorService exe = Executors
for(int i=
exe
try{
doneSignal
// TODO: handle exception
e
}finally{
System
System
}
exe
long end=System
System
}
}
運行結果比較
根據運行結果看
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27648.html