import java.util.concurrent.atomic.*; public class testee { public static void main (AtomicReference [] args){ Maquina maq = new Maquina(); AtomicReference a = new AtomicReference("cha"); AtomicReference b = new AtomicReference("refrigerante"); AtomicReference c = new AtomicReference("refri"); AtomicReference d = new AtomicReference("cha"); Fornecedor cha = new Fornecedor(a, maq); Fornecedor refri = new Fornecedor(b, maq); Cliente r1 = new Cliente(c, maq); Cliente c1 = new Cliente(d, maq); cha.start(); refri.start(); c1.start(); r1.start(); } } class Maquina { AtomicInteger quantidadeC; AtomicInteger quantidadeR; AtomicBoolean tem; public Maquina(){ this.quantidadeC = new AtomicInteger(20); this.quantidadeR = new AtomicInteger(40); // this.quantidadeR = 40; this.tem = new AtomicBoolean(true); } public void abastecer(){ while(tem.get()){ try{ wait(); } catch(InterruptedException e){} } if(quantidadeC.get() <= 1){ quantidadeC.set(30); System.out.println("Abastecendo o Chá"); } else if(quantidadeR.get() <= 1){ quantidadeR.set(60); System.out.println("Abastecendo o Refrigerante"); } tem.set(true); notifyAll(); } public void retirarC(){ while(!tem.get()){ try{ wait(); } catch (InterruptedException e) {} } for (int i = 0; i < 6 && tem.get(); i++) { try{ Thread.sleep(2000); } catch (InterruptedException e){} if(quantidadeC.get() >= 1){ quantidadeC.getAndDecrement(); System.out.println("Retirando um chá!"); } else { System.out.println("Não tem chá suficiente"); tem.set(false); } } tem.set(false); notifyAll(); } public void retirarR(){ while(!tem.get()){ try{ wait(); } catch (InterruptedException e) {} } for (int i = 0; i < 10 && tem.get(); i++) { try{ Thread.sleep(2000); } catch (InterruptedException e){} if(quantidadeR.get() >= 1){ quantidadeR.getAndDecrement(); System.out.println("Retirando um refrigerante!"); } else { System.out.println("Não tem refrigerante suficiente"); tem.set(false); } } tem.set(false); notifyAll(); } } class Fornecedor extends Thread { AtomicReference id; Maquina maq; public Fornecedor(AtomicReference id, Maquina maq){ this.id = id; this.maq = maq; } public void run(){ for (int i = 0; i < 10; i++) { try{ Thread.sleep(10000); } catch (InterruptedException e) {} maq.abastecer(); } } } class Cliente extends Thread { AtomicReference id; Maquina maq; public Cliente(AtomicReference id, Maquina maq){ this.id = new AtomicReference(id); this.maq = maq; } public void run(){ for (int i = 0; i < 10; i++) { // Cliente de Chá if(this.id.toString().contains("cha")){ AtomicBoolean ehvazio = new AtomicBoolean(false); maq.retirarC(); // Cliente de Refrigerante } else { maq.retirarR(); } } } }