Thread + Sync

1 resposta
R

Olá, possuo os dois códigos abaixo

public class Teste1 extends Thread {

	String valor;

	Teste2 produtora;
	BlockingQueue<String> workRequestList;
	Map<String, String> workersList;

	public Teste1(Teste2 produtora) {
		this.produtora = produtora;
		this.workRequestList = this.produtora.workRequestList;
		this.workersList = this.produtora.workersList;
	}

	public void run() {
		while (true) {
			try {
				this.valor = this.workRequestList.take();
				System.out.println("RECEBI VALOR: ");
				if (!this.workersList.isEmpty()) {
					System.out.println("RECEBI VALORES: ");
					System.out.print(valor);
					System.out.print(this.workersList.get(valor));
				} 
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}

public class Teste2 {

	BlockingQueue<String> workRequestList;
	Map<String, String> workersList;
	Teste1 cons;
	
	public Teste2() {
		this.workRequestList = new LinkedBlockingQueue<String>();
		this.workersList = Collections.synchronizedMap(new LinkedHashMap<String, String>());
		this.cons = new Teste1(this);
		this.cons.start();
	}
	
	public static void main (String[] args) {
		Teste2 prod = new Teste2();
		try {
			prod.workRequestList.put("WORKER0001");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			System.out.println("ESPERA");
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		prod.workersList.put("WORKER0001", "787878");
	}
}

Por que o que esta dentro da thread nao executa até o “RECEBI VALORES”. Executa somente até o “RECEBI VALOR”. Qual seria a solução?

1 Resposta

ViniGodoy

Coloque a espera na Thread1, e retire da Thread2.

O que acontece é que a Thread2 produz muito mais lentamente que a Thread2 consome. Nesse caso, cada take() da Thread1 deixará a lista vazia, e o código nunca entrará no if.

Criado 13 de fevereiro de 2011
Ultima resposta 13 de fev. de 2011
Respostas 1
Participantes 2