今天在论坛里面帮网友写了个,已调试通过1个生成者对应20个消费者,写的比较随意,没单独写类,用的内部类.如果那个地方有错,欢迎大家指正,批评.
public class ExecutorServiceTest {
private static int maxTask = 80;
private static Object lock = new Object();
public static void main(String[] args) {
final List tasks = new ArrayList();
final ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new Runnable() {
public void run() {
while (!Thread.interrupted()) {
try {
synchronized (tasks) {
if (tasks.size() == maxTask)
tasks.wait();
}
synchronized (lock) {
if (tasks.size() != maxTask) {
tasks.add(new Object());
System.out.println("生产任务");
lock.notifyAll();
Thread.yield();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
for (int i = 0; i < 20; i++) {
exec.execute(new Runnable() {
public void run() {
while (!Thread.interrupted()) {
try {
synchronized (lock) {
if (tasks.size() == 0)
lock.wait();
}
synchronized (tasks) {
if (tasks.size() > 0) {
tasks.remove(0);
System.out.println("处理任务");
tasks.notifyAll();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
exec.shutdown();
}
}
private static int maxTask = 80;
private static Object lock = new Object();
public static void main(String[] args) {
final List tasks = new ArrayList();
final ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new Runnable() {
public void run() {
while (!Thread.interrupted()) {
try {
synchronized (tasks) {
if (tasks.size() == maxTask)
tasks.wait();
}
synchronized (lock) {
if (tasks.size() != maxTask) {
tasks.add(new Object());
System.out.println("生产任务");
lock.notifyAll();
Thread.yield();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
for (int i = 0; i < 20; i++) {
exec.execute(new Runnable() {
public void run() {
while (!Thread.interrupted()) {
try {
synchronized (lock) {
if (tasks.size() == 0)
lock.wait();
}
synchronized (tasks) {
if (tasks.size() > 0) {
tasks.remove(0);
System.out.println("处理任务");
tasks.notifyAll();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
exec.shutdown();
}
}
本文展示了一个使用Java ExecutorService实现的生产者消费者模型示例,该模型包含1个生产者和20个消费者,用于处理任务队列。通过synchronized关键字和wait/notifyAll方法来协调生产者和消费者的同步问题。
339

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



