每个知识点都尽量涉及到,
但每种队列应用的场景都不一样的,
如何应用合适的队列,这就是经验了。
如何在队列里容纳多个线程,及多个线程处理同一个队列?
应该算是JAVA里比较深入的思考了。
producer
package demo.thread;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TransferQueue;
public class Producer implements Runnable {
private final TransferQueue<String> queue;
public Producer(TransferQueue<String> queue) {
this.queue = queue;
}
private String produce() {
return "Your lucky number " + (new Random().nextInt(100));
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
while (true) {
if (queue.hasWaitingConsumer()) {
queue.transfer(produce());
}
TimeUnit.SECONDS.sleep(1);
}
} catch (InterruptedException e){
}
}
}
consumer
package demo.thread;
import java.util.concurrent.TransferQueue;
public class Consumer implements Runnable{
private final TransferQueue<String> queue;
public Consumer(TransferQueue<String> queue) {
this.queue = queue;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
System.out.println("Consumer " + Thread.currentThread().getName() + queue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
main
package demo.thread;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TransferQueue;
public class ThreadMain {
public static void main(String[] args) {
TransferQueue<String> queue = new LinkedTransferQueue<String>();
Thread producer = new Thread(new Producer(queue));
producer.setDaemon(true);
producer.start();
for (int i = 0; i < 10; i++) {
Thread consumer = new Thread(new Consumer(queue));
consumer.setDaemon(true);
consumer.start();
try {
Thread.sleep(1000L);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
output
Consumer Thread-1Your lucky number 33
Consumer Thread-2Your lucky number 51
Consumer Thread-3Your lucky number 8
Consumer Thread-4Your lucky number 35
Consumer Thread-5Your lucky number 29
Consumer Thread-6Your lucky number 8
Consumer Thread-7Your lucky number 46
Consumer Thread-8Your lucky number 20
Consumer Thread-9Your lucky number 15
Consumer Thread-10Your lucky number 67