File: threadring.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 (94 lines) | stat: -rw-r--r-- 2,223 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
/**
 * The Computer Language Benchmarks Game
 * http://shootout.alioth.debian.org/
 * contributed by Klaus Friedel
 */

import java.util.*;

public class threadring {

  public static long startTime;
  public static final int THREAD_COUNT = 503;

  // The scheduler for cooperative Multithreading
  static class Scheduler extends Thread{
    private final List<CooperativeThread> threads = Collections.synchronizedList(new ArrayList<CooperativeThread>());
    private int rrIndex = -1;

    public void start(CooperativeThread t){
      threads.add(t);
    }

    public void run() {
      for(;;){ // Scheduler will run foerever
        CooperativeThread nextThread;
        synchronized (threads){
          rrIndex++;
          if(rrIndex >= threads.size()) rrIndex = 0;
          nextThread = threads.get(rrIndex);
        }
        nextThread.handleMessage();
      }
    }
  }

  static abstract class CooperativeThread{
    public abstract void handleMessage();
  }

  static class MessageThread extends CooperativeThread{
      MessageThread nextThread;
      String name;
      Integer msg;

      public MessageThread(MessageThread nextThread, int name) {
        this.name = "" + name;
        this.nextThread = nextThread;
      }

      public void handleMessage(){
        if(msg == null) return;
        if(msg == 0){
          System.out.println(getName());
          System.exit(0);
        }
        nextThread.put(msg - 1);
        msg = null;
      }

      void put(Integer message){
        msg = message;
      }

      String getName() {
        return name;
      }
    }


  public static void main(String args[]) throws Exception{
    int hopCount = Integer.parseInt(args[0]);

    MessageThread thread = null;
    MessageThread last = null;
    for (int i = THREAD_COUNT; i >= 1 ; i--) {
      thread = new MessageThread(thread, i);
      if(i == THREAD_COUNT) last = thread;
    }
    // close the ring:
    last.nextThread = thread;

    Scheduler scheduler = new Scheduler();
    // start all Threads
    MessageThread t = thread;
    do{
      scheduler.start(t);
      t = t.nextThread;
    }while(t != thread);
    scheduler.start();

    // inject message
    thread.put(hopCount);
  }
}