文章目录
- 题目
- 难点
- 源代码
题目
编写一个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++;
}
}
}
}