700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > java进程生产者消费者_生产者与消费者(多线程经典案例)

java进程生产者消费者_生产者与消费者(多线程经典案例)

时间:2019-03-13 03:05:29

相关推荐

java进程生产者消费者_生产者与消费者(多线程经典案例)

packageorg.lx.multithreading;classInfo//定义信息类{privateStringname="罗星";//定义name属性privateStringcontent="JAVA初学者";//定义content属性privatebooleanflag=false;//设置标志位publicsynchronizedvoidset(Stringname,Stringcontent){if(!flag){//方法每次执行的时候都检查一下标志位状态,从而判断时候进行生产try{super.wait();

}catch(InterruptedExceptione){

e.printStackTrace();

}

}this.setName(name);//设置名称try{

Thread.sleep(300);

}catch(InterruptedExceptione){

e.printStackTrace();

}this.setContent(content);//设置内容flag=false;//改变标志位,表示可以取走super.notify();//唤醒线程}publicsynchronizedvoidget(){if(flag){方法每次执行的时候都检查一下标志位状态,从而判断时候进行取出try{super.wait();

}catch(InterruptedExceptione){

e.printStackTrace();

}

}try{

Thread.sleep(300);

}catch(InterruptedExceptione){

e.printStackTrace();

}

System.out.println(this.getName()+"-->"+this.getContent());

flag=true;//改变标志位,表示可以生成super.notify();

}publicvoidsetName(Stringname){this.name=name;

}publicStringgetName(){returnthis.name;

}publicvoidsetContent(Stringcontent){this.content=content;

}publicStringgetContent(){returnthis.content;

}

}classProducerimplementsRunnable//通过Runnable实现多线程{publicInfoinfo=null;//保存Info引用publicProducer(Infoinfo){this.info=info;

}publicvoidrun(){booleanflag=false;//定义标记位for(inti=0;i<50;i++){if(flag){this.info.set("罗星","JAVA初学者");

flag=false;

}else{this.info.set("Solitary","Coder");

flag=true;

}

}

}

};classConsumerimplementsRunnable{//消费者类privateInfoinfo=null;publicConsumer(Infoinfo){this.info=info;

}publicvoidrun(){for(inti=0;i<50;i++){this.info.get();

}

}

};//测试代码publicclassMultiThreading

{publicstaticvoidmain(String[]args){

Infoinfo=newInfo();//实例化Info对象Producerpro=newProducer(info);//生产者Consumercon=newConsumer(info);//消费者newThread(pro).start();newThread(con).start();

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。