Saturday, May 25, 2013

Threads II

Here is another example of threads.
Get the code here.

/**
 * An enum with a single value is probably the ultimate singleton.
 * However, it can get real ugly real soon as far as testability is concerned.
 *
 * @author megha birmiwal
 */
public enum StatisticsCollector {
// can override methods in enums like this
//      INFLATED_STATS
//              public int getTimesCalled() {
//                      return count * 10;
//              }
//      },
        STATS;
        private static int count = 0;
        private static double timeSum = 0;
        synchronized public void reportStat(double time) {
                count++;
                timeSum += time;
        }
        public int getTimesCalled() {
                return count;
        }
        public double getAverage() {
                return timeSum / getTimesCalled();
        }
}

/**
 * Reports a given time to the {@link StatisticsCollector}.
 *
 * @author megha birmiwal
 */
public class TimeReporter implements Runnable {
        private final int timeToReport;
        private final int count;
        public TimeReporter(int timeToReport, int count) {
                this.timeToReport = timeToReport;
                this.count = count;
        }
        @Override
        public void run() {
                for (int i = 0; i < count; i++) {
                        StatisticsCollector.STATS.reportStat(timeToReport);
                }
        }
}
public class Main {
        public static void main(String args[]) throws InterruptedException {
                Thread threadX1 = new Thread(new TimeReporter(100, 10000));
                threadX1.start();
                Thread threadX2 = new Thread(new TimeReporter(100, 10000));
                threadX2.start();
                Thread threadY = new Thread(new TimeReporter(200, 10000));
                threadY.start();
                threadX1.join();
                threadX2.join();
                threadY.join();
                int timesCalled = StatisticsCollector.STATS.getTimesCalled();
                double average = StatisticsCollector.STATS.getAverage();
                System.out.println("Total Calls: " + (timesCalled));
                System.out.println("Average Time: " + (average));
        }
}

No comments:

Post a Comment