-
Notifications
You must be signed in to change notification settings - Fork 1
/
BankRobbery.java
108 lines (88 loc) · 2.89 KB
/
BankRobbery.java
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
101
102
103
104
105
106
107
108
package com.jyotindersingh;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class BankRobbery {
public static final int MAX_PASSWORD = 9999;
public static void main(String[] args) {
Random random = new Random();
Vault vault = new Vault(random.nextInt(MAX_PASSWORD));
List<Thread> threads = new ArrayList<>();
threads.add(new AscendingHackerThread(vault));
threads.add(new DescendingHackerThread(vault));
threads.add(new PoliceThread());
for(Thread thread : threads) {
thread.start();
}
}
private static class Vault {
private int password;
public Vault(int password) {
this.password = password;
}
public boolean isCorrectPassword(int guess) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
return this.password == guess;
}
}
private static abstract class HackerThread extends Thread {
protected Vault vault;
public HackerThread(Vault vault) {
this.vault = vault;
this.setName(this.getClass().getSimpleName());
this.setPriority(Thread.MAX_PRIORITY);
}
@Override
public void start() {
System.out.println("Starting thread " + this.getName());
super.start();
}
}
private static class AscendingHackerThread extends HackerThread {
public AscendingHackerThread(Vault vault) {
super(vault);
}
@Override
public void run() {
for (int guess = 0; guess < MAX_PASSWORD; guess++) {
if (vault.isCorrectPassword(guess)) {
System.out.println(this.getName() + " guessed the password " + guess);
System.exit(0);
}
}
}
}
private static class DescendingHackerThread extends HackerThread {
public DescendingHackerThread(Vault vault) {
super(vault);
}
@Override
public void run() {
for (int guess = MAX_PASSWORD; guess >= 0; guess--) {
if (vault.isCorrectPassword(guess)) {
System.out.println(this.getName() + " guess the password " + guess);
System.exit(0);
}
}
}
}
private static class PoliceThread extends Thread {
@Override
public void run() {
for (int i = 10; i > 0; --i) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i);
}
System.out.println("Game over for you hackers");
System.exit(0);
}
}
}