File: message.java

package info (click to toggle)
groovy2 2.2.2%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 23,916 kB
  • sloc: java: 136,570; xml: 948; sh: 486; makefile: 67; ansic: 64
file content (100 lines) | stat: -rw-r--r-- 2,361 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/* The Computer Language Benchmarks Game
 http://shootout.alioth.debian.org/

 contributed by Mattias Bergander
 */

import java.util.LinkedList;
import java.util.List;

public class message {
    public static final int numberOfThreads = 500;

    public static int numberOfMessagesToSend;

    public static void main(String args[]) {
        numberOfMessagesToSend = Integer.parseInt(args[0]);

        MessageThread chain = null;
        for (int i = 0; i < numberOfThreads; i++) {
            chain = new MessageThread(chain);
            new Thread(chain).start();
        }

        for (int i = 0; i < numberOfMessagesToSend; i++) {
            chain.enqueue(new MutableInteger(0));
        }

    }
}

class MutableInteger {
    int value;

    public MutableInteger() {
        this(0);
    }

    public MutableInteger(int value) {
        this.value = value;
    }

    public MutableInteger increment() {
        value++;
        return this;
    }

    public int intValue() {
        return value;
    }
}

class MessageThread implements Runnable {
    MessageThread nextThread;

    List<MutableInteger> list = new LinkedList<MutableInteger>();

    MessageThread(MessageThread nextThread) {
        this.nextThread = nextThread;
    }

    public void run() {
        if (nextThread != null) {
            while (true) {
                nextThread.enqueue(dequeue());
            }
        } else {
            int sum = 0;
            int finalSum = message.numberOfThreads * message.numberOfMessagesToSend;
            while (sum < finalSum) {
                sum += dequeue().intValue();
            }
            System.out.println(sum);
            System.exit(0);
        }
    }

    /**
     * @param message
     */
    public void enqueue(MutableInteger message) {
        synchronized (list) {
            list.add(message);
            if (list.size() == 1) {
                list.notify();
            }
        }
    }

    public MutableInteger dequeue() {
        synchronized (list) {
            while (list.size() == 0) {
                try {
                    list.wait();
                } catch (InterruptedException e) {
                }
            }
            return list.remove(0).increment();
        }
    }
}