使用wait()方法和notifyAll()方法完成线程间的通信

 

下面程序的功能是:在queue类中设置了公共资源n,分别有生产者线程和消费者线程。生产者生产一次,消费者消费一次。
Queue类:
package cn.hpu.queue;

public class Queue {

	//队列中的公共资源,数值n
	private int n;
	//设置标志,用来判断队列中是否有数值
	boolean flag=false;
	
	public synchronized int get() {
		
		if(!flag) {
			//如果队列中没有数值,那就进行等待。直到有数值时才进行消费
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("消费"+n);
		flag=false;//消费完成,将标志设置为false,表示现在没有数值了
		notifyAll();
		return n;
		
	}

	public synchronized void set(int n) {
		//如果队列中已经有数值了,那就等待,不再进行生产
		if(flag) {
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("生产:"+n);
		this.n = n;
		notifyAll();
		flag=true;//生产完成,表示现在已经有数值了
	}
	
	
}

 

生产者类:

package cn.hpu.queue;

//生产者类
public class Producer implements Runnable{

	Queue queue;
	public Producer(Queue queue){
		this.queue=queue;
	}
	
	public void run() {
		int i=0;
		while(true) {
			queue.set(i++);
			//线程休眠1s,为了更好的演示线程的安全问题
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
}

消费者类:

package cn.hpu.queue;
//消费者类
public class Consumer implements Runnable{

	Queue queue;
	public Consumer(Queue queue) {
		this.queue=queue;
	}
	
	public void run() {
		int i=0;
		while(true) {
			queue.get();
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	
}

测试类:

package cn.hpu.queue;

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Queue queue=new Queue();
		//生产者线程
		new Thread(new Producer(queue)).start();
		//消费者线程
		new Thread(new Consumer(queue)).start();
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值