编程实现计数器累加,要求如下:
1)计数器必须封装在一个类中;
2)启动多个线程去对计数器累加;
3)对计数器进行同步处理;

解决方案 »

  1.   

    这样是否满足你的要求?public class Test {    public static void main(String[] args) {
    Counter counter = new Counter();
    for (int i = 0; i < 10; i++) {
        MyThread mt = new MyThread(counter);
        // 启动10个线程, 操作计数器
        mt.start();
    }
        }
    }class Counter {
        // 计数器的同步锁
        public Object mutex = new Object();    private int count;    public Counter() {
    this.count = 0;
        }    public void add() {
    this.count++;
        }    public int getCount() {
    return count;
        }}class MyThread extends Thread {    private Counter counter;    public MyThread(Counter counter) {
    this.counter = counter;
        }    @Override
        public void run() {
    while (true) {
        synchronized (counter.mutex) {
    counter.add();
    System.err.println("Thread " + this + " 执行add操作,计数器值为:"
    + this.counter.getCount());
        }
        try {
    Thread.sleep(1 * 1000);
        } catch (InterruptedException e) {
    e.printStackTrace();
        }
    }
        }}
      

  2.   


    public void add() {
        this.count++;
    }应该给这个方法加同步锁会更合理点。
      

  3.   

    都是java的 楼主要用Java搞这个题目 ?