Java线程间通信

对于我们的银行账户,两个线程之间并没有联系,这就会出现余额不足但是还能取钱的状况,为了解决这个问题,我们就使用线程间通信来解决

wait()方法:中断方法的执行,使线程等待

notify()方法:唤醒处于等待的某一线程,使其等待结束

notifyAll()方法:唤醒处于等待的所有线程,使其等待结束

package Threadproj;

public class Consumer implements Runnable {
    Queue queue;
    Consumer(Queue queue){
    	this.queue=queue;
    }
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
        while(true) {
        	queue.getN();
        	try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
	}

}

 

package Threadproj;

public class Producer implements Runnable{
    Queue queue;
    Producer(Queue queue){
    	this.queue=queue;
    }
	
	@Override
	public void run() {
		int i=0;
		while(true) {
			queue.setN(i++);
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

}

 

package Threadproj;

public class Queue {
	private int n;
	boolean flag = false;

	public int getN() {
		// flag为false的时候容器中没有数据了,线程等待
		if (!flag) {
			try {
				synchronized (this) {
					this.wait();
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("消费" + n);
		// 消费完毕,容器中没数据了
		flag = false;
		notifyAll();
		return n;
	}

	public void setN(int n) {
		// flag为true的时候容器中有数据了,线程等待
		if (flag) {
			try {
				synchronized (this) {
					this.wait();
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("生产" + n);
		this.n = n;
		// 生产完毕,容器中已经有数据
		flag = true;
		notifyAll();
	}

}

 

package Threadproj;

public class TestA {
	public static void main(String[] args) {
		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、付费专栏及课程。

余额充值