多线程之生产消费

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程之生产消费相关的知识,希望对你有一定的参考价值。

package mysd;

public class Main {
	public static void main(String[] args) {
		DianY dy=new DianY();
		ChangJ cj=new ChangJ(dy);
		Xiaof xf=new Xiaof(dy);
		Thread td=new Thread(cj);
		Thread td2=new Thread(cj);
		
		Thread td1=new Thread(xf);
		Thread td11=new Thread(xf);
//		td2.start();
		td.start();
		td1.start();
		td11.start();
		
	}

}



package mysd;


public class DianY {

int top=30;

public synchronized void add(){

if(this.top>=50){

try {

this.wait();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}else{

top++;

System.out.println("生产者生产的"+top+"个产品。");

notifyAll();

}

}

public synchronized void de(){

if(this.top<=0){

try {

this.wait();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}else{

top--;

System.out.println("消费的"+top+"个产品。");

notifyAll();

}

}


}



package mysd;


public class ChangJ implements Runnable{

private DianY dy;

public ChangJ(DianY dy){

this.dy=dy;

}


@Override

public void run() {

for(;;){

try {

Thread.sleep(50);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

dy.add();

}

}


}



package mysd;


public class Xiaof implements Runnable{

private DianY dy;

public  Xiaof(DianY dy) {

// TODO Auto-generated constructor stub

this.dy=dy;

}


@Override

public void run() {

// TODO Auto-generated method stub

for(;;){

try {

Thread.sleep(50);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

dy.de();

}

}



}


以上是关于多线程之生产消费的主要内容,如果未能解决你的问题,请参考以下文章

软件分享免费多线程下载神器,可完全替代IDM(支持Mac&Windows)

Java学习-多线程交互

java多线程--“朴素版”生产者消费者问题

多线程之生产者消费者模式

Java多线程系列--“基础篇”11之 生产消费者问题

Java--多线程之生产者消费者模式;线程池ExecutorService