Skip to content

Instantly share code, notes, and snippets.

@CansecoDev
Created November 29, 2018 05:39
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 CansecoDev/f436cf6f65a3419485a1b976b9a0b439 to your computer and use it in GitHub Desktop.
Save CansecoDev/f436cf6f65a3419485a1b976b9a0b439 to your computer and use it in GitHub Desktop.
An example of java multithreading; 2 cashiers attending one client each one simultaneously
public class ThreadedCashier {
public static void main(String[] args) {
Client client1 = new Client("Client 1", new int[]{2, 2, 1, 5, 2, 3, 1, 6, 1, 2, 1, 5});
Client client2 = new Client("Client 2", new int[]{1, 1, 1, 1, 1, 2, 1, 1, 2, 1, 1, 2});
long initialTime = System.currentTimeMillis();
Cashier cashier1 = new Cashier("Cashier 1", client1, initialTime);
Cashier cashier2 = new Cashier("Cashier 2", client2, initialTime);
System.out.println("OPEN DOORS");
cashier1.start();
cashier2.start();
try {
cashier1.join();
cashier1.join();
} catch (InterruptedException ex) {
}
System.out.println("CLOSE DOORS");
}
}
class Cashier extends Thread {
private String cashierName;
public String getCashierName() {
return cashierName;
}
private Client currentClient;
public Client getCurrentClient() {
return currentClient;
}
private long initialTime;
public Cashier(String name, Client cli, long time) {
cashierName = name;
currentClient = cli;
initialTime = time;
}
@Override
public void run() {
System.out.println(this.cashierName + " START PROCESSING "
+ this.currentClient.getClientName() + " TIME: "
+ (System.currentTimeMillis() - this.initialTime) / 1000
+ "SEC");
for (int i = 0; i < this.currentClient.getBuyBox().length; i++) {
this.waitSeconds(currentClient.getBuyBox()[i]);
System.out.println(this.cashierName + " PROCESSED " + (i + 1)
+ " OF " + this.currentClient.getClientName() + " TIME: "
+ (System.currentTimeMillis() - this.initialTime) / 1000
+ "SEC");
}
System.out.println(this.cashierName + " ENDS WITH "
+ this.currentClient.getClientName() + " TIME: "
+ (System.currentTimeMillis() - this.initialTime) / 1000
+ "SEC");
}
private void waitSeconds(int segundos) {
try {
Thread.sleep(segundos * 1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
class Client {
private String clientName;
public String getClientName() {
return clientName;
}
public int[] getBuyBox() {
return buyBox;
}
private int[] buyBox;
public Client(String name, int[] box) {
clientName = name;
buyBox = box;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment