Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- import java.util.concurrent.Semaphore;
- class H2OMachine {
- String[] molecule;
- int count;
- public H2OMachine() {
- molecule = new String[3];
- count = 0;
- }
- static Semaphore hydrogen = new Semaphore(1);
- static Semaphore oxygen = new Semaphore(1);
- static Semaphore hHere = new Semaphore(0);
- static Semaphore countLock = new Semaphore(1);
- public void hydrogen() throws InterruptedException {
- // TODO: 3/29/20 synchronized logic here
- hydrogen.acquire();
- countLock.acquire();
- molecule[count++]="H";
- if(count==3){
- System.out.println("Hydrogen atom 2 arrived");
- System.out.println(String.join("-", molecule));
- count=0;
- countLock.release();
- hydrogen.release();
- oxygen.release();
- return;
- }
- System.out.println("Hydrogen atom 1 arrived");
- hHere.release();
- countLock.release();
- }
- public void oxygen() throws InterruptedException {
- // TODO: 3/29/20 synchronized logic here
- oxygen.acquire();
- hHere.acquire();
- countLock.acquire();
- System.out.println("Oxygen arrived");
- molecule[count++]="O";
- countLock.release();
- hydrogen.release();
- }
- }
- class H2OThread extends Thread {
- H2OMachine molecule;
- String atom;
- public H2OThread(H2OMachine molecule, String atom) {
- this.molecule = molecule;
- this.atom = atom;
- }
- public void run() {
- if ("H".equals(atom)) {
- try {
- molecule.hydrogen();
- } catch (Exception e) {
- }
- } else if ("O".equals(atom)) {
- try {
- molecule.oxygen();
- } catch (Exception e) {
- }
- }
- }
- }
- public class Main {
- public static void main(String[] args) throws InterruptedException {
- // TODO: 3/29/20 Simulate with multiple scenarios
- H2OMachine molecule = new H2OMachine();
- int n = 120;
- H2OThread[] threads = new H2OThread[n];
- for (int i = 0; i < n; i++) {
- if (i%3==0) {
- threads[i] = new H2OThread(molecule, "O");
- } else threads[i] = new H2OThread(molecule, "H");
- }
- Arrays.stream(threads).forEach(Thread::start);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement