Java中线程通信

1. 多个线程在操作同一份资源时,其操作如果一致的,则不需要使用线程之间的通信,如多个线程卖票。如果操作不一致,则可能需要线程通信。

2. java中线程之间的通信一般利用wait和notify方法来实现的

2.1  wait(),wait()方法使得当前线程必须要等待,等到另外一个线程调用notify()或者notifyAll()方法当前的线程必须拥有当前对象的monitor,也即lock,就是锁。线程调用wait()方法,释放它对锁的拥有权,然后等待另外的线程来通知它(通知的方式是notify()或者notifyAll()方法),这样它才能重新获得锁的拥有权和恢复执行。要确保调用wait()方法的时候拥有锁,即,wait()方法的调用必须放在synchronized方法或synchronized块中。注意:sleep方法不会释放锁,而wait会释放锁。

2.2 notify方法,该方法同样只能被当前的锁所调用,即只能在同步中使用。调用之后会会唤醒阻塞线程池中的线程的某一个,一般为第一个。唤醒之后并不是立即执行,而是和其他的线程一起参加竞争。

lass Resource{
	private int count=0;
	private boolean flag=false;
	//定义生产资源
	public synchronized void produce(){
		while(flag)
			try{this.wait();}catch(Exception e){};
		System.out.println(Thread.currentThread().getName()+"...生产..."+count++);
		flag=true;
		//this.notify();
		this.notifyAll();
	}
	//定义消费
	public synchronized void consume(){
		while(!flag)
			try{this.wait();}catch(Exception e){};
		System.out.println(Thread.currentThread().getName()+".......消费..."+count);
		flag=false;
		//this.notify();
		this.notifyAll();
	}
	
}
class Produce implements Runnable{
	Resource res;
	//定义共享资源
	public Produce(Resource res){
		this.res=res;
	}
	public void run(){
		while(true){
			res.produce();
		}
	}
}

class Consume implements Runnable{
	Resource res;
	public Consume(Resource res){
		this.res=res;
	}
	public void run(){
		while(true){
			res.consume();
		}
	}
}

public class app {
	public static void main(String[] args) {
		Resource res=new Resource();
		Consume con=new Consume(res);
		Produce pro=new Produce(res);
		
		new Thread(pro).start();
		new Thread(pro).start();
		new Thread(con).start();
		new Thread(con).start();
}}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值