想达到这么一个目的:一个线程是消费者,多个线程是生产者。当有多个生产者生产出东西来,消费者马上消费,否则一直wait。消费者消费的同时不影响生产者生产,生产者生产时同样也不会影响消费者消费。看代码
package test;
import java.util.concurrent.ConcurrentLinkedQueue;
public class ThreadTest implements Runnable {
static ConcurrentLinkedQueue<String> concurrentBlockQueue = new ConcurrentLinkedQueue<String>();
static Object _lock = new Object();
@Override
public void run() {
while (true) {
synchronized (_lock) {
while (concurrentBlockQueue.isEmpty()) {
try {
System.out.println("waiting...");
_lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println(concurrentBlockQueue.poll());
}
}
public static class Producer implements Runnable {
@Override
public void run() {
for (int i = 0; i < 1000000; i++) {
concurrentBlockQueue.add(i + "A");
synchronized (_lock) {
_lock.notify();
}
}
}
}
public static void main(String[] args) {
Thread myThread = new Thread(new ThreadTest());
myThread.start();
Producer pd = new Producer();
new Thread(pd).start();;
for (int i = 0; i < 1000000; i++) {
concurrentBlockQueue.add(i + "");
synchronized (_lock) {
_lock.notify();
}
}
}
}
本文介绍了一个线程同步的实现案例,其中一个线程作为消费者,多个线程作为生产者。使用了ConcurrentLinkedQueue来实现非阻塞的数据交换,并通过synchronized关键字及wait和notify方法来协调生产者和消费者的运行。
2630

被折叠的 条评论
为什么被折叠?



