案例介绍
生产者:生产者,消费者消费者,消费品,蛋糕,消费品存放队列CakeQueue
代码说明
生产者生产商/h3>
<代码>公共类生产商延伸线程{
私人最终CakeQueue CakeQueue;
私有静态int cakeNo=0;
公共生产商(字符串名称,CakeQueue CakeQueue) {
超级(名称);
这一点。cakeQueue=cakeQueue;
}
公共空间run () {
尝试{
而(真){
thread . sleep (1000);
蛋糕蛋糕=new蛋糕(createCakeNo ());
this.cakeQueue.put(蛋糕);
}
}捕捉(InterruptedException e) {
}
}
私有静态同步int createCakeNo () {
返回cakeNo + +;
}
}
代码>
消费者消费者
<代码>公共类消费者线程{延伸
私人最终CakeQueue CakeQueue;
公共消费(字符串名称,CakeQueue CakeQueue) {
超级(名称);
这一点。cakeQueue=cakeQueue;
}
公共空间run () {
尝试{
而(真){
蛋糕蛋糕=cakeQueue.take ();
thread . sleep (1000);
}
}捕捉(InterruptedException e) {
}
}
}
代码>
蛋糕蛋糕/h3>
<代码>/* *
*蛋糕
*/公共类蛋糕{
私人最终int没有;
公共蛋糕(int) {
这一点。没有=;
}
公共int getNo () {
返回this.no;
}
公共字符串toString () {
返回“蛋糕没有。”+不+“]”;
}
}
代码>
队列CakeQueue
<代码>/* *
*存放蛋糕的队列
*/公开课CakeQueue {
私人[]cakeList最后蛋糕;
私人int头;
私人int尾巴;
私人int计数器;
公共CakeQueue (int num) {
这一点。cakeList=新蛋糕(num);
这一点。头=0;
这一点。尾=0;
这一点。counter=0;
}//同步放入一个蛋糕
公共同步空白把蛋糕蛋糕)抛出InterruptedException {
System.out.println (Thread.currentThread () . getname() +”提出:没有“+ cake.getNo ());
而(计数器祝辞=cakeList.length) {
wait ();
}
cakeList(尾巴)=蛋糕;
尾=(尾+ 1)% cakeList.length;
计数器+ +;
notifyAll ();
}//同步获取一个蛋糕
公共同步蛋糕带()抛出InterruptedException {
而(计数器& lt;=0) {
wait ();
}
蛋糕蛋糕=cakeList(头);
头=(头+ 1)% cakeList.length;
计数器,;
notifyAll ();
system . out。println (“- - - - - -”+ Thread.currentThread () . getname() +“:没有“+ cake.getNo ());
返回蛋糕;
}
}
代码>
启动文件
<代码>公共类主要{
公共静态void main (String [] args) {
CakeQueue CakeQueue=new CakeQueue (3);
新的生产者(“Producer-1:“cakeQueue) .start ();
新的生产者(“Producer-2:“cakeQueue) .start ();
新的生产者(“Producer-3:“cakeQueue) .start ();
新的消费者(消费者1:“cakeQueue) .start ();
新的消费者(消费者2:“cakeQueue) .start ();
新的消费者(“Consumer-3:“cakeQueue) .start ();
}
}代码>
运行结果
<代码>/* * *蛋糕 */公共类蛋糕{ 私人最终int没有; 公共蛋糕(int) { 这一点。没有=; } 公共int getNo () { 返回this.no; } 公共字符串toString () { 返回“蛋糕没有。”+不+“]”; } } 代码>
队列CakeQueue
<代码>/* * *存放蛋糕的队列 */公开课CakeQueue { 私人[]cakeList最后蛋糕; 私人int头; 私人int尾巴; 私人int计数器; 公共CakeQueue (int num) { 这一点。cakeList=新蛋糕(num); 这一点。头=0; 这一点。尾=0; 这一点。counter=0; }//同步放入一个蛋糕 公共同步空白把蛋糕蛋糕)抛出InterruptedException { System.out.println (Thread.currentThread () . getname() +”提出:没有“+ cake.getNo ()); 而(计数器祝辞=cakeList.length) { wait (); } cakeList(尾巴)=蛋糕; 尾=(尾+ 1)% cakeList.length; 计数器+ +; notifyAll (); }//同步获取一个蛋糕 公共同步蛋糕带()抛出InterruptedException { 而(计数器& lt;=0) { wait (); } 蛋糕蛋糕=cakeList(头); 头=(头+ 1)% cakeList.length; 计数器,; notifyAll (); system . out。println (“- - - - - -”+ Thread.currentThread () . getname() +“:没有“+ cake.getNo ()); 返回蛋糕; } } 代码>
启动文件
<代码>公共类主要{ 公共静态void main (String [] args) { CakeQueue CakeQueue=new CakeQueue (3); 新的生产者(“Producer-1:“cakeQueue) .start (); 新的生产者(“Producer-2:“cakeQueue) .start (); 新的生产者(“Producer-3:“cakeQueue) .start (); 新的消费者(消费者1:“cakeQueue) .start (); 新的消费者(消费者2:“cakeQueue) .start (); 新的消费者(“Consumer-3:“cakeQueue) .start (); } }代码>
运行结果