import java.awt.geom.AffineTransform; import java.lang.invoke.SwitchPoint; import java.util.concurrent.Semaphore; import java.util.*; public class Main { public static void main(String args[]) { init(); List c_atoms = new ArrayList<>(); List h_atoms = new ArrayList<>(); List o_atoms = new ArrayList<>(); for(int i = 0; i < 20; i++) { c_atoms.add(new C()); } for(int i = 0; i < 40; i++) { h_atoms.add(new H()); } for(int i = 0; i < 20 ;i++) { o_atoms.add(new O()); } for(int i = 0; i < 20 ; i++) { c_atoms.get(i).start(); } for(int i = 0; i < 40; i++) { h_atoms.get(i).start(); } for(int i = 0; i < 20 ;i++) { o_atoms.get(i).start(); } try { for(int i = 0; i < 20 ; i++) { c_atoms.get(i).join(); } for(int i = 0; i < 40; i++) { h_atoms.get(i).join(); } for(int i = 0; i < 20 ;i++) { o_atoms.get(i).join(); } } catch (InterruptedException e) { } } static Semaphore c; static Semaphore h; static Semaphore o; static Semaphore c_created; static Semaphore h_created; static Semaphore o_created; static Semaphore boss; private static void init() { c = new Semaphore(2); h = new Semaphore(4); o = new Semaphore(2); c_created = new Semaphore(0); h_created = new Semaphore(0); o_created = new Semaphore(0); boss = new Semaphore(0); } static class C extends Thread { private void excecute() throws InterruptedException { c.acquire(1); c_created.release(6); h_created.acquire(1); o_created.acquire(1); boss.release(6); System.out.println("C bonding"); c.release(1); } @Override public void run() { try { excecute(); } catch (InterruptedException e) { } } } static class H extends Thread { private void excecute() throws InterruptedException{ h.acquire(1); c_created.acquire(1); h_created.release(4); o_created.acquire(1); boss.acquire(1); System.out.println("H bonding"); h.release(); } @Override public void run() { try { excecute(); } catch (InterruptedException e) { } } } static class O extends Thread { private void excecute() throws InterruptedException{ o.acquire(1); c_created.acquire(1); h_created.acquire(1); o_created.release(6); boss.acquire(1); System.out.println("O bonding"); o.release(1); } @Override public void run() { try { excecute(); } catch (InterruptedException e) { } } } }