今天在论坛里面帮网友写了个,已调试通过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();
}
}