发布于 2016-07-05 10:18:58 | 130 次阅读 | 评论: 0 | 来源: 网友投递
Java程序设计语言
java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台(即JavaEE(j2ee), JavaME(j2me), JavaSE(j2se))的总称。
import java.util.List;
public class Consume implements Runnable {
private List container = null;
private int count;
public Consume(List lst) {
this.container = lst;
}
public void run() {
while (true) {
synchronized (container) {
if (container.size() == 0) {
try {
container.wait();// 容器为空,放弃锁,等待生产
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
container.remove(0);
container.notify();
System.out.println("我吃了" + (++count) + "个");
}
}
}
}
import java.util.List;
public class Product implements Runnable {
private List container = null;
private int count;
public Product(List lst) {
this.container = lst;
}
public void run() {
while (true) {
synchronized (container) {
if (container.size() > MultiThread.MAX) {
// 如果容器超过了最大值,就不要在生产了,等待消费
try {
container.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
container.add(new Object());
container.notify();
System.out.println("我生产了" + (++count) + "个");
}
}
}
}
import java.util.ArrayList;
import java.util.List;
public class MultiThread {
private List container = new ArrayList();
public final static int MAX = 5;
public static void main(String args[]) {
MultiThread m = new MultiThread();
new Thread(new Consume(m.getContainer())).start();
new Thread(new Product(m.getContainer())).start();
}
public List getContainer() {
return container;
}
public void setContainer(List container) {
this.container = container;
}
}
我生产了1个
我吃了1个
我生产了2个
我生产了3个
我生产了4个
我生产了5个
我生产了6个
我生产了7个
我吃了2个
我生产了8个
我吃了3个
我生产了9个
我吃了4个
我吃了5个
我吃了6个
我吃了7个
我吃了8个
我生产了10个
我生产了11个
我吃了9个
我生产了12个
我吃了10个
......