生产者与消费者使用一个注类和四个类部类组成.
下面展示一些 内联代码片
。
package java_day06_Thread;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.Util;
import jdk.nashorn.internal.objects.Global;
public class System021{
public static void main(String[] args) {
Container ctr1=new Container();
//生产
Produce pd1=new Produce(ctr1);
pd1.start();
//消费
Consumer cs1=new Consumer(ctr1);
cs1.start();
}
}
//西瓜
class WaterMelon{
}
//容器
class Container{
//设置容器大小为5
WaterMelon[] wt=new WaterMelon[5];
int index=0;
//set
// new一个西瓜
WaterMelon wm=new WaterMelon();
public synchronized void setWater(){
//满了
while(index==wt.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//唤起其他线程
this.notifyAll();
wt[index]=wm;
System.out.println("生产者-----生产一个瓜");
index++;
}
public synchronized void getWater(){
while (index==0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
index--;
wm=wt[index];
this.notifyAll();
System.out.println("消费者-----消费一个瓜");
}
}
//生产者
class Produce extends Thread{
private Container container;
public Produce(Container container) {
this.container = container;
}
@Override
public void run() {
while (true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
container.setWater();
}
}
}
//消费者
class Consumer extends Thread{
private Container container;
public Consumer(Container container) {
this.container = container;
}
@Override
public void run() {
while (true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
container.getWater();
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。