Skip to content

Instantly share code, notes, and snippets.

@fakruboss
Created October 1, 2021 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fakruboss/519d33e291eecb5219d09bdc73ce058b to your computer and use it in GitHub Desktop.
Save fakruboss/519d33e291eecb5219d09bdc73ce058b to your computer and use it in GitHub Desktop.
package thread.creation;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class PoliceHacker {
public static final int MAX_PASSWORD = 24999;
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 DescendingHackerThread(vault));
threads.add(new AscendingHackerThread(vault));
threads.add(new PoliceThread());
for (Thread thread : threads) {
thread.start();
}
}
private static class Vault {
private final int password;
Vault(int password) {
this.password = password;
}
public boolean isCorrectPassword(int guess) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
return this.password == guess;
}
}
private abstract static class HackerThread extends Thread {
protected Vault vault;
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 {
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 {
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() + " guessed 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 u hackers");
System.exit(0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment