mercredi 25 février 2015

Pattern to communicate with a thread

I have a class OuterClass that contains a List and there is a thread ListWorker that is started in OuterClass that is adding some elements to the list. Based on a function call to OuterClass , it should be able to inform the thread to delete elements. What is the best practise? The intention is not to have a blocking data structure (no synchronization) and therefore having a single thread work on List.



Class OuterClass {
List<String> list = new ArrayList<String>();
ListWorker worker = new ListWorker(list);

deleteLastElement() {
worker.setDeleteLastElement(true);
}
}


The worker



ListWorker implements Runnable {

private List<String> list;
private volatile boolean deleteLastElement;

public void setDeleteLastElement(boolean deleteLastElement) {
this.deleteLastElement = deleteLastElement;
}

public ListWorker(List<String> list) {
this.list = list;
}

public void run() {
while(true) {
//add random elements

if(deleteLastElement) {
//delete last element
//set the boolean now to false
}
}
}

Aucun commentaire:

Enregistrer un commentaire