WikiStart: ProcessorSolution.txt

File ProcessorSolution.txt, 2.9 KB (added by 152071, 5 years ago)
Line 
1import java.util.ArrayList;
2import java.util.List;
3import java.util.Random;
4import java.util.concurrent.Semaphore;
5
6public class ProcessorSolution extends Thread {
7
8 public static Semaphore canGenerate = new Semaphore(5);
9 public static Semaphore processEvent = new Semaphore(0);
10
11 public static Random random = new Random();
12 static List<EventGeneratorSolution> scheduled = new ArrayList<>();
13
14 public static void main(String[] args) throws InterruptedException {
15 // TODO: kreirajte Processor i startuvajte go negovoto pozadinsko izvrsuvanje
16 Processor processor = new Processor();
17 processor.start();
18
19
20 for (int i = 0; i < 100; i++) {
21 EventGeneratorSolution eventGenerator = new EventGeneratorSolution();
22 register(eventGenerator);
23 //TODO: startuvajte go eventGenerator-ot
24 eventGenerator.start();
25 }
26
27
28 // TODO: Cekajte 20000ms za Processor-ot da zavrsi
29 processor.join(20_000);
30
31 // TODO: ispisete go statusot od izvrsuvanjeto
32 if (processor.isAlive()) {
33 processor.interrupt();
34 System.out.println("Terminated scheduling");
35 } else {
36 System.out.println("Finished scheduling");
37 }
38
39 }
40
41 public static void register(EventGeneratorSolution generator) {
42 scheduled.add(generator);
43 }
44
45 /**
46 * Ne smee da bide izvrsuva paralelno so generate() metodot
47 */
48 public static void process() {
49 System.out.println("processing event");
50 }
51
52
53 public void run() {
54
55 while (!scheduled.isEmpty()) {
56 try {
57 // TODO: cekanje na nov generiran event
58 processEvent.acquire();
59
60 // TODO: povikajte go negoviot process() metod
61 canGenerate.acquire(5);
62 process();
63 canGenerate.release(5);
64 } catch (InterruptedException e) {
65 e.printStackTrace();
66 }
67 }
68
69 System.out.println("Done scheduling!");
70 }
71}
72
73
74class EventGeneratorSolution extends Thread {
75
76 public Integer duration;
77
78 public EventGeneratorSolution() throws InterruptedException {
79 this.duration = Processor.random.nextInt(1000);
80 }
81
82 /**
83 * Ne smee da bide povikan paralelno kaj poveke od 5 generatori
84 */
85 public static void generate() {
86 System.out.println("Generating event: ");
87 }
88
89 @Override
90 public void run() {
91 try {
92 Thread.sleep(this.duration);
93 ProcessorSolution.canGenerate.acquire();
94 generate();
95 ProcessorSolution.processEvent.release();
96 ProcessorSolution.canGenerate.release();
97 } catch (InterruptedException e) {
98 e.printStackTrace();
99 }
100 }
101
102
103}