File: process.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 (86 lines) | stat: -rw-r--r-- 1,679 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
/* The Great Computer Language Shootout
   http://shootout.alioth.debian.org/
 
   contributed by Isaac Gouy 
*/


public class process {

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

      EndLink chainEnd = new EndLink(null, n);
      chainEnd.start();
      Link chain = chainEnd;
         
      for (int i=2; i<=n; i++){
         Link link = new Link(chain);             
         link.start();
         chain = link;
      }

      chain.put(0);     
      try { chainEnd.join(); } catch (InterruptedException e){} 

      System.out.println(chainEnd.count);
      System.exit(0);
   }
}


class Link extends Thread {
   Link next;
   int message = -1;
   boolean busy = false;
   
   Link(Link t){
      next = t;
   }

   public void run() { 
      for (;;) next.put(this.take());          
   }

   synchronized void put(int m) {
      while (busy)
         try { wait(); } catch (InterruptedException e){}   
      busy = true;
      message = m;
      notifyAll();

      while (message != -1)
         try { wait(); } catch (InterruptedException e){}  
      busy = false;
      notifyAll();            
   }

   synchronized int take() {
      while (message == -1)
         try { wait(); } catch (InterruptedException e){}  

      int m = message;
      message = -1;
      notifyAll();
      return m+1;             
   }
}


class EndLink extends Link {
   public int count = 0;
   private int finalcount;
   
   EndLink(Link t, int i){
      super(t);
      finalcount = i;
   }

   public void run() { 
      do 
         count += this.take(); 
      while (count < finalcount);       
   }
}

// vim: set ts=4 ft=java