題目
編寫一個Java程序,該程序將啓動4個線程,其中3個是擲硬幣線程,1個是主線程。每個擲硬幣線程將連續擲出若干次硬幣(10次以內,次數隨機生成);主線程將打印出正面出現的總次數以及正面出現的概率。
難點
因爲要計算數量以及出現概率,所以必須將所有子線程內的數據同步到主線程內。
源代碼
Coin.java
package com.web.homework03;
public class Coin{
public static void main(String[] args) throws InterruptedException {
test test = com.web.homework03.test.getTest();
Thread[] trr = new Thread[3];
for (int i = 0; i < 3; i++) {
trr[i] = new Thread(new Roll(test), "線程" + (i + 1));
}
for (Thread thread : trr) {
thread.start();
}
for (Thread thread : trr) {
thread.join();
}
System.out.println("正面總次數爲:"+test.getRoll());
System.out.println("正面總次數爲:"+test.getRandoms());
System.out.println("出現正面的概率爲:"+(double)test.getRoll()/test.getRandoms());
}
}
Roll.java
package com.web.homework03;
public class Roll implements Runnable{
private test test01;
public Roll(test test){
this.test01 = test;
}
@Override
public void run() {
test01.method();
}
}
test.java
package com.web.homework03;
import java.util.Random;
public class test {
private int randoms;
private int roll;
public int getRandoms() {
return randoms;
}
public void setRandoms(int randoms) {
this.randoms = randoms;
}
public int getRoll() {
return roll;
}
public void setRoll(int roll) {
this.roll = roll;
}
private test() {
}
private static final test test = new test();
public static test getTest() {
return test;
}
public synchronized void method() {
Random random = new Random();
int times = random.nextInt(10);
randoms += times;
for (int i =0;i<times;i++){
if (random.nextBoolean()){
roll++;
}
}
}
}