[SOLVED] Blocking Queues - how?
Hi. I've got some small prog as you can see here... There are locks used in it.
I want to understand the difference and the purpose of using blocking queues that's why i'd like to have this prog using them.
Can anybody be so helpful to do this for me or just to give some tips how to start with this issue?
Thx in advance!
Code:
import java.util.concurrent.locks.*;
class Text {
Lock lock = new ReentrantLock();
Condition txtWritten = lock.newCondition();
Condition txtSupplied = lock.newCondition();
String txt = null;
boolean newTxt = false;
void setTextToWrite(String s) {
lock.lock();
try {
if (txt != null) {
while (newTxt == true)
txtWritten.await();
}
txt = s;
newTxt = true;
txtSupplied.signal();
} catch (InterruptedException exc) {
} finally {
lock.unlock();
}
}
String getTextToWrite() {
lock.lock();
try {
while (newTxt == false)
txtSupplied.await(); // can be Interrupted
newTxt = false;
txtWritten.signal();
return txt;
} catch (InterruptedException exc) {
return null;
} finally {
lock.unlock();
}
}
}
Code:
class Author extends Thread {
Teksty txtArea;
Author(Teksty t) {
txtArea=t;
}
public void run() {
String[] s = { "One", "Two", "Three", "Four", "Five", "Six", null };
for (int i=0; i<s.length; i++) {
try {
sleep((int)(Math.random() * 1000));
} catch(InterruptedException exc) { }
txtArea.setTextToWrite(s[i]);
}
}
}
Code:
class Writer extends Thread {
Teksty txtArea;
Writer(Teksty t) {
txtArea=t;
}
public void run() {
String txt = txtArea.getTextToWrite();
while(txt != null) {
System.out.println("-> " + txt);
txt = txtArea.getTextToWrite();
}
}
}
Code:
public class Coord {
public static void main(String[] args) {
Teksty t = new Teksty();
Thread t1 = new Author(t);
Thread t2 = new Writer(t);
t1.start();
try { Thread.sleep(3000); } catch(Exception exc) {}
t2.start();
}
}