import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;

public class VotingSystem { public static void main(String[] args) { List votes = Collections.synchronizedList(new ArrayList()); ExecutorService executor = Executors.newFixedThreadPool(4); for (int i = 0; i < 4; i++) { executor.execute(new Voter(votes)); } executor.shutdown(); while (!executor.isTerminated()) { // 等待所有的投票线程结束 } System.out.println("总票数:" + votes.size()); } }

class Voter implements Runnable { private List votes;

public Voter(List<String> votes) {
    this.votes = votes;
}

@Override
public void run() {
    for (int i = 0; i < 100; i++) {
        votes.add("票");
    }
    System.out.println(Thread.currentThread().getName() + " 投票完成");
}

}

编写一个投票系统要求:开启4个线程进行投票票放入一个集合中每个线程投票100张循环100次向集合中加入100个元素投票完成后控制台输出集合中的票数为400

原文地址: http://www.cveoy.top/t/topic/bU78 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录