|
Spec-Zone .ru
спецификации, руководства, описания, API
|
Thread object to Executor.execute? Would such an invocation make sense? Why or why not?
Answer: Thread implements the Runnable interface, so you can pass an instance of Thread to Executor.execute. However it doesn't make sense to use Thread objects this way. If the object is directly instantiated from Thread, its run method doesn't do anything. You can define a subclass of Thread with a useful run method but such a class would implement features that the executor would not use.
Drop class.
Solution: The
java.util.concurrent.BlockingQueue interface defines a get method that blocks if the queue is empty, and a put methods that blocks if the queue is full. These are effectively the same operations defined by Drop except that Drop is not a queue! However, there's another way of looking at Drop: it's a queue with a capacity of zero. Since there's no room in the queue for any elements, every get blocks until the corresponding take and every take blocks until the corresponding get. There is an implementation of BlockingQueue with precisely this behavior:
.
BlockingQueue is almost a drop-in replacement for Drop. The main problem in
import java.util.Random;
import java.util.concurrent.BlockingQueue;
public class Producer implements Runnable {
private BlockingQueue<String> drop;
public Producer(BlockingQueue<String> drop) {
this.drop = drop;
}
public void run() {
String importantInfo[] = {
"Mares eat oats",
"Does eat oats",
"Little lambs eat ivy",
"A kid will eat ivy too"
};
Random random = new Random();
try {
for (int i = 0;
i < importantInfo.length;
i++) {
drop.put(importantInfo[i]);
Thread.sleep(random.nextInt(5000));
}
drop.put("DONE");
} catch (InterruptedException e) {}
}
}
Consumer:
import java.util.Random;
import java.util.concurrent.BlockingQueue;
public class Consumer implements Runnable {
private BlockingQueue<String> drop;
public Consumer(BlockingQueue<String> drop) {
this.drop = drop;
}
public void run() {
Random random = new Random();
try {
for (String message = drop.take();
! message.equals("DONE");
message = drop.take()) {
System.out.format("MESSAGE RECEIVED: %s%n",
message);
Thread.sleep(random.nextInt(5000));
}
} catch (InterruptedException e) {}
}
}
ProducerConsumerExample, we simply change the declaration for the drop object:
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
public class ProducerConsumerExample {
public static void main(String[] args) {
BlockingQueue<String> drop =
new SynchronousQueue<String> ();
(new Thread(new Producer(drop))).start();
(new Thread(new Consumer(drop))).start();
}
}