Two Threads
Hello all,
i'm building a application that have 2 threads running at same time, but they are thowing RuntimeException (IllegalStateMonitorException) when are made call for the methods wait() e notifyAll.
I would want that ListenerThread stay running while application is running and WriterThread stay running only when have messages. The attribute shutdown tell for threads that application still are running.
The codes are below:
//Type Thread
public enum ChannelType{
WRITER, LISTENER;
}
// Thread Class of my problem
public class Channel extends Thread {
private ChannelType type;
private Manager manager;
public Channel(ChannelType type, Manager manager) {
this.type = type;
this.manager = manager;
}
@Override
public void run() {
super.run();
switch (type) {
// Thread 1
case WRITER:
// Enquanto n鉶 finalizar aplica玢o
while (!manager.isShutdown()) {
// Sen鉶 tiver mensagens pra enviar
if (manager.getMessages().isEmpty()) {
try {
System.out.println("Parando thread de escrita");
wait();
} catch (InterruptedException e) {
System.out.println("Acordando thread");
}
} else {
// Envia mensagens
for (; !manager.getMessages().isEmpty();) {
System.out.println("Enviando mensagem: " + manager.getMessages().pop());
}
}
}
break;
// Thread 2
case LISTENER:
// Enquanto n鉶 finalizar aplica玢o
while (!manager.isShutdown()) {
// Fica aguardando recebimento de mensagens
if (manager.getMessages().isEmpty()){
System.out.println("Aguardando o recebimento de mensagens");
}
// Acorda as threads
else {
System.out.println("Acorda");
notifyAll();
}
}
break;
}
}
}
\\ Manager of the Threads
public class Manager {
private Stack<String> messages;
private Channel writer;
private Channel listener;
private boolean shutdown;
/**
*
*/
public Manager() {
this.messages = new Stack<String>();
// Cria e inicia a thread
this.writer = new Channel(ChannelType.WRITER, this);
this.writer.start();
// Cria e inicia a thread
this.listener = new Channel(ChannelType.LISTENER, this);
this.listener.start();
}
public void addMessage(String message){
this.messages.add(0, message);
}
public Stack<String> getMessages() {
return messages;
}
public synchronized boolean isShutdown() {
return shutdown;
}
public void setShutdown(boolean shutdown) {
this.shutdown = shutdown;
}
}
\\ MAIN
public class Main {
public static void main(String[] args) {
Manager manager = new Manager();
manager.addMessage("teste 1");
manager.addMessage("teste 2");
manager.addMessage("teste 3");
manager.addMessage("teste 4");
manager.addMessage("teste 5");
manager.addMessage("teste 6");
manager.addMessage("teste 7");
manager.addMessage("teste 8");
manager.addMessage("teste 9");
manager.addMessage("teste 10");
}
}
If anybody have solution for my problem, please, reply me. Thanks all.

