package trabalho1; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Main { public static void main(String[] args) { Buffer buffer = new Buffer(); ScheduledExecutorService threadsEscritoras = Executors.newScheduledThreadPool(1); ExecutorService threadsLeitoras = Executors.newFixedThreadPool(4); try { for (int i = 0; i < 120; i++) { threadsLeitoras.execute(new Leitor(buffer)); // cria e tenta iniciar as threads leitoras e as coloca no estado executável (pronto -> executando e executando -> pronto) fornecendo acesso a cada uma das 4, no pool, ao buffer. threadsEscritoras.scheduleAtFixedRate(new Escritor(buffer), 0, 300, TimeUnit.MILLISECONDS); // cria e tenta iniciar as threads escritoras e as coloca no estado executável, fornecendo acesso a cada uma ao buffer, uma por vez. } } catch (Exception exception) { exception.printStackTrace(); } threadsEscritoras.shutdownNow(); threadsLeitoras.shutdownNow(); while(!threadsEscritoras.isTerminated() ){ try { Thread.sleep(10); } catch (InterruptedException e) { System.out.println("Thread: "+Thread.currentThread().getName()+ " não finalizada."); } } System.exit(0); } } ////////////////////////////////////// package trabalho1; public class Buffer { private int mensagem = 0; private int threadLeitor = 0; private boolean occupied = false; public synchronized void escrever(int msg) { while (occupied) { try { wait(); } catch (InterruptedException e) { System.out.println("A thread: "+Thread.currentThread().getName()+ " não escreveu a mensagem."); } } mensagem = msg; occupied = true; String nomethread = Thread.currentThread().getName(); System.out.println(nomethread +"-"+"MENSAGEM ENVIADA: "+ msg); notifyAll(); } public synchronized int ler() { String nomethread = Thread.currentThread().getName(); while (!occupied) { try { wait(); } catch (InterruptedException e) { System.out.println("A thread: "+Thread.currentThread().getName()+ " não leu a mensagem."); } } if(threadLeitor < 4){ int msgRecebida = mensagem; threadLeitor++; System.out.println(nomethread +"-"+"Mensagem recebida: "+ msgRecebida); } if(threadLeitor == 4){ occupied = false; threadLeitor = 0; notify(); } return mensagem; } } //////////////////////////////// package trabalho1; public class Escritor implements Runnable { private Buffer mensagem; public Escritor(Buffer msg) { this.mensagem = msg; } @Override public void run() { for (int i = 1; i <= 120; i++) { mensagem.escrever(i); } } } ///////////////////////////// package trabalho1; public class Leitor implements Runnable { private Buffer mensagem; public Leitor(Buffer msg) { this.mensagem = msg; } @Override public void run() { for (int i = 0; i < 120; i++) { while(mensagem.ler() != 0){} } } }