Java 多线程模拟年会入场:统计人数和彩票号码
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/ofl0 著作权归作者所有。请勿转载和采集!