用JAVA代码1 某公司组织年会会议入场时有两个入口 在入场时每位员工都能获取一张双色球彩票假设公司有100个员工 利用多线程模拟年会入场过程并分别统计每个入口入场的人数以及每个员工拿到的彩票的号码。
import java.util.Random;
public class AnnualMeeting { private static int numEmployees = 100; private static int numEntrances = 2; private static int numTickets = 2; private static int[] entranceCounts = new int[numEntrances]; private static int[][] tickets = new int[numEmployees][numTickets];
public static void main(String[] args) {
Thread[] threads = new Thread[numEmployees];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new Employee(i));
threads[i].start();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < numEntrances; i++) {
System.out.println("Entrance " + (i+1) + " count: " + entranceCounts[i]);
}
for (int i = 0; i < numEmployees; i++) {
System.out.println("Employee " + (i+1) + " tickets: [" + tickets[i][0] + ", " + tickets[i][1] + "]");
}
}
static class Employee implements Runnable {
private int id;
private Random random;
public Employee(int id) {
this.id = id;
this.random = new Random();
}
@Override
public void run() {
int entrance = random.nextInt(numEntrances);
synchronized (AnnualMeeting.class) {
entranceCounts[entrance]++;
tickets[id][0] = random.nextInt(33) + 1;
tickets[id][1] = random.nextInt(16) + 1;
}
}
}
原文地址: https://www.cveoy.top/t/topic/fqGN 著作权归作者所有。请勿转载和采集!