Java多线程——等待唤醒机制

转载来源
在开始讲解等待唤醒机制之前,有必要搞清一个概念——

线程之间的通信:

多个线程在处理同一个资源,但是处理的动作(线程的任务)却不相同。通过一定的手段使各个线程能有效的利用资源。而这种手段即—— 等待唤醒机制。

等待唤醒机制所涉及到的方法:

  • wait() :等待,将正在执行的线程释放其执行资格和执行权,并存储到线程池中。

  • notify():唤醒,唤醒线程池中被wait()的线程,一次唤醒一个,而且是任意的。

  • notifyAll(): 唤醒全部:可以将线程池中的所有wait() 线程都唤醒。

其实,所谓唤醒的意思就是让 线程池中的线程具备执行资格。必须注意的是,这些方法都是在 同步中才有效。同时这些方法在使用时必须标明所属锁,这样才可以明确出这些方法操作的到底是哪个锁上的线程。

仔细查看JavaAPI之后,发现这些方法 并不定义在 Thread中,也没定义在Runnable接口中,却被定义在了Object类中,为什么这些操作线程的方法定义在Object类中?
因为这些方法在使用时,必须要标明所属的锁,而锁又可以是任意对象。能被任意对象调用的方法一定定义在Object类中。

接下来,我们先从一个简单的示例入手:

如上图说示,输入线程 想Resource中输入name ,sex , 输出线程从资源中输出,先要完成的任务是:

  1. 当input发现Resource中没有数据时,开始输入,输入完成后,叫output来输出。如果发现有数据,就wait();

  2. 当output发现Resource中没有数据时,就wait() ;当发现有数据时,就输出,然后,叫醒input来输入数据。

这个问题的关键在于,如何来做到交替运行。

下面看具体的代码实现:

public class Resource {
	private String name ;
	private String sex;
	private boolean flag = false;
	
	public synchronized void set(String name , String sex){
		
		if(flag)
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//设置成员变量
			this.name = name;
			this.sex = sex;
			//设置之后,Resource中有值,将标记该为 true ,
			flag = true;
			//唤醒output
			this.notify();	
	}
	public synchronized void out(){
		if(!flag)
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		//输出线程将数据输出
		System.out.println("The name is : " + name + " &&  The sex is : " + sex);
		//改变标记,以便输入线程输入数据
		flag = false;		
		//唤醒input,进行数据输入
		this.notify();	
	}
 
}
 
public class Input implements Runnable {
 
	private Resource r;
	public Input(Resource r){
		this.r = r;
	}
	
	@Override
	public void run() {
		int count = 0 ; 
		while(true){
			if(count == 0){
				r.set("Tom", "man");
			}else{
				r.set("Lily", "woman");
			}
			//在连个数据之间进行切换。
			count = (count + 1)%2;
		}
	}
 
}
 
public class Output implements Runnable {
 
	private Resource r ;
	public Output(Resource r ){
		this.r = r;
	}
	@Override
	public void run() {
		while(true){
			r.out();
		}
 
	}
}
 
public class ResourceDemo {
 
	public static void main(String[] args) {
		//资源对象
		Resource r = new Resource();
		//任务对象
		Input in = new Input(r);
		Output out = new Output(r);
		//线程对象
		Thread t1 = new Thread(in);
		Thread t2 = new Thread(out);
		//开启线程
		t1.start();
		t2.start();		
	}
}

在这个例子中,我们应用了等待唤醒机制,这是最简单的应用,下面我们来看看等待唤醒机制的经典问题:生产者,消费者问题!

当然也是,从最简单的问题开始看起:即单个消费者,生产者。这个例子和上个例子极其相似,因此不再赘述。接下来,主要谈一下,多生产者,多消费者的情形。

看下例子代码:

public class Resource {
	private String name;
	private int count = 1;
	private boolean flag ;
	
	public synchronized void set(String name){
		if(flag){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
			this.name = name + count;
			count++;
			
			System.out.println(Thread.currentThread().getName() 
						+ "The producer name is :++++++++++++++ " + this.name);
			
			flag = true;
			
			this.notify();
			
	}
	
	public synchronized void out(){
		if(!flag){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	
		System.out.println(Thread.currentThread().getName() + 
				 "The consumer name is : ---------------------------" + this.name);
		flag = false;
		
		this.notify();
		
	}
 
}
 
public class Producer implements Runnable {
 
	private Resource r;
	public Producer(Resource r){
		this.r = r;
	}
	@Override
	public void run() {
 
		while(true){
			r.set("馒头");
		}
		
	}
}
 
public class Consumer implements Runnable {
 
	private Resource r;
	public Consumer(Resource r ){
		this.r = r;
	}
	@Override
	public void run() {
 
		while(true){
			r.out();
		}		
	}
}
 
public class ProConDemo {
 
	public static void main(String[] args) {
 
		//资源对象
		Resource r = new Resource();
		//任务对象
		Producer pro = new Producer(r);
		Consumer con = new Consumer(r);
		//线程对象,两个生产者,两个消费者
		Thread t1 = new Thread(pro);
		Thread t2 = new Thread(pro);
		
		Thread t3 = new Thread(con);
		Thread t4 = new Thread(con);
		
		//开启线程
		t1.start();
		t2.start();
		t3.start();
		t4.start();
	}
 
}

但是经过运行,我们会发现这样的问题:

发现:生产者生产的商品没有被消费就生产了新的商品。

经过分析,发现,产生这种状况的根源是:

1,本方唤醒了本方。

2,被唤醒的本方没有判断标记。

为此,我们要做的改进是——将if 判断改为 while 标记,保证,每次被wait的线程在醒了之后,都得再次判断标记。进过修改,再次运行之后,会发现新的问题又来了,产生了死锁。经过分析,这个问题的根源在于,本方唤醒了本方,被唤醒的本方判断标记后,发现,标记不成立,就继续等待,因此,再也没有活着的线程。为此,我们需要唤醒,所有的线程,就用到了 notifyAll() 。将线程池中,所有等待的线程都叫醒。

经过修改后的代码成功的解决了上述的问题。

修改后的代码为:

public class Resource {
	private String name;
	private int count = 1;
	private boolean flag ;
	
	public synchronized void set(String name){
		//用while 确保线程醒了后再次,判断标记。
		while(flag){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
			this.name = name + count;
			count++;
			
			System.out.println(Thread.currentThread().getName() 
						+ "The producer name is :++++++++++++++ " + this.name);
			
			flag = true;
			//唤醒所有被等待的线程
			this.notifyAll();
			
	}
	
	public synchronized void out(){
		//用while 确保线程醒了后再次,判断标记。
		while(!flag){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	
		System.out.println(Thread.currentThread().getName() + 
				 "The consumer name is : ---------------------------" + this.name);
		flag = false;
		//唤醒所有被等待的线程
		this.notifyAll();
		
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值