黑马程序员:线程间通信介绍:wait()、notify()、Lock、Condition等介绍

---------------------- ASP.Net+Android+IOS开发.Net培训、期待与您交流! ----------------------

线程间通信:多个线程在使用同一个资源,但操作的动作不同

等待唤醒机制:
线程创建后都存放在内存中的线程池,wait()的线程也存放在线程池中
wait();等待 public final void wait() throws InterruptedException
写wait时注意要处理异常,暂时写成try{锁名.wait();}catch(Exception e){}
notify();唤醒 (谁先等待就先唤醒谁) 当两方(比如一个存数据,一个取数据)各有两个线程及以上时,使用while标记判断后,容易造成两方都进入等待状态
若不写锁名,会出现java.lang.IllegalMonitorStateException错误
notifyAll();唤醒线程池中的所有。当两方各有两个线程及以上时,防止两方全是等待状态,可以用notifyAll(); 这个比较通用,但是又出现了抢资源的状况,所以JDK5.0及之后提供了升级版的解决方案Lock Condition


重点:
以上方法都只能放在synchronized中,因为要对持有监视器(锁)的线程操作,所以要使用在同步中,否则会出现
IllegalMonitorStateException异常(RuntimeException子类),该异常在以下情况出现:如果当前线程不是此对象监视器的所有者


使用以上方法的时候要标示锁
即 若synchronized(r){} 则r.wait(); r.notify()也同理  若为this,可以不写


为什么这些操作线程的方法要定义在Object类中?
因为这些方法在操作同步中线程时,都必须要标示它们所操作线程持有的锁
只有同一个锁上的被等待线程,可以被同一个锁上的notify唤醒。
不可以对不同锁中的线程进行唤醒。
即:wait和notify必须是同一个锁


而锁可以是任意对象,所有可以被任意对象调用的方法定义在Object类中

示例:

class Res
{
	String name;
	String sex;
	boolean flag = false;
}
class Input implements Runnable
{
	private Res r;
	Input(Res r)
	{
		this.r = r;
	}
	public void run()
	{
		int x = 0;
		while(true)
		{
			synchronized(r)
			{
				if (r.flag)
					try{r.wait();}catch(Exception e){}
				if(x==0)
				{
						r.name = "mike";
						r.sex = "man";
				}
				else
				{
						r.name = "小红";
						r.sex = "女";
				}
				r.flag = true;
				r.notify();
			}
				x = (x+1)%2; //为了if和else都能执行到
		}
	}
}
class Output implements Runnable
{
	private Res r;
	Output(Res r)
	{
		this.r = r;
	}
	public void run()
	{
		while(true)
			synchronized(r)
			{
				if (!r.flag)
					try{r.wait();}catch(Exception e){}
				System.out.println(r.name+"...."+r.sex);
				r.flag = false;
				r.notify();
			}
	}
}

class InputOutputDemo
{
	public static void main(String[] args)
	{
		Res r = new Res();
		Input in = new Input(r);
		Output out = new Output(r);
		Thread t1 = new Thread(in);
		Thread t2 = new Thread(out);
		t1.start();
		t2.start();
	}
}

优化后的代码如下:

class Res
{
	private String name;
	private String sex;
	private boolean flag = false;
	public synchronized void set(String name,String sex)
	{
		if (flag)
			try{this.wait();}catch(Exception e){}
		this.name = name;
		this.sex = sex;
		flag = true;
		this.notify();
	}
	public synchronized void out()
	{
		if (!flag)
			try{this.wait();}catch(Exception e){}
		System.out.println(name+"...."+sex);
		flag = false;
		this.notify();
	}
}
class Input implements Runnable
{
	private Res r;
	Input(Res r)
	{
		this.r = r;
	}
	public void run()
	{
		int x = 0;
		while(true)
		{
			if(x==0)
			{
				r.set("Mike","man");
			}
			else
			{
				r.set("小雅","女人");
			}
			x = (x+1)%2; //为了if和else都能执行到
		}
	}
}
class Output implements Runnable
{
	private Res r;
	Output(Res r)
	{
		this.r = r;
	}
	public void run()
	{
		while(true)
			r.out();
	}
}

class InputOutputDemo
{
	public static void main(String[] args)
	{
		Res r = new Res();
		new Thread(new Input(r)).start();
		new Thread(new Output(r)).start();
	}
}

示例:生产者消费者
/*
生产者和消费者
生产出一个,则消费一个
要求4个线程操作,各两个线程
思路:
1.定义一个资源,生产者和消费者使用的资源,比如商品
2.定义生产者类,并实现Runnable接口
3.定义消费者类,并实现Runnable接口
4.解决多线程安全问题
*/

class Resource
{
	private String shopname;
	private int count = 1;
	private boolean flag = false;
	public synchronized void set(String shopname)
	{
		while(flag)
		{
			try
			{
				this.wait();
			}
			catch(Exception e)
			{
				
			}
		}
		this.shopname = shopname+count++;
		System.out.println(Thread.currentThread().getName()+"--生产者--"+this.shopname);//因这里存在局部变量shopname,故shopname前若不加this,打印的是局部变量shopname
		flag = true;
		this.notifyAll();
	}
	public synchronized void get()
	{
		while(!flag)
		{
			try
			{
				this.wait();
			}
			catch(Exception e)
			{
				
			}
		}
		System.out.println(Thread.currentThread().getName()+"----消费者----"+this.shopname);
		flag = false;
		this.notifyAll();
	}
}

class Producer implements Runnable
{
	private Resource r;
	Producer(Resource r)
	{
		this.r = r;
	}
	public void run()
	{
		while(true)
			r.set("+商品+");
	}
}
class Consumer implements Runnable
{
	private Resource r;
	Consumer(Resource r)
	{
		this.r = r;
	}
	public void run()
	{
		while(true)
			r.get();
	}
}
class ProducerConsumer
{
	public static void main(String[] args) {
		Resource r = new Resource();
		new Thread(new Producer(r)).start();
		new Thread(new Producer(r)).start();
		new Thread(new Consumer(r)).start();
		new Thread(new Consumer(r)).start();
	}
}

JDK1.5中提供了多线程升级解决方案
将synchronized替换成Lock操作
将Object中的wait,notify,notifyAll,替换成Condition对象
该对象可以对Lock锁进行获取,并且可以该对象可以操作指定对象唤醒、等待,解决了全部唤醒(notifyAll(),nosignalAll())的弊端
示例:
/*
生产者和消费者 JDK1.5升级版
生产出一个,则消费一个
要求4个线程操作,各两个线程
思路:
1.定义一个资源,生产者和消费者使用的资源,比如商品
2.定义生产者类,并实现Runnable接口
3.定义消费者类,并实现Runnable接口
4.解决多线程安全问题
*/

import java.util.concurrent.locks.*;
class Resource
{
	private String shopname;
	private int count = 1;
	private boolean flag = false;
	private ReentrantLock lock = new ReentrantLock();//Windows平台下可以写成private Lock lock = new ReentrantLock(); 而linux平台下若那样写的话会有不兼容类型错误。但在Windows平台下编译成功后的class文件可以在linux中运行
	private Condition condition_producer = lock.newCondition();
	private Condition condition_consumer = lock.newCondition();
	public void set(String shopname) throws InterruptedException
	{
		lock.lock();
		try
		{
			while(flag)
				condition_producer.await();
			this.shopname = shopname+count++;
			System.out.println(Thread.currentThread().getName()+"--生产者--"+this.shopname);//因这里存在局部变量shopname,故shopname前若不加this,打印的是局部变量shopname
			flag = true;
			condition_consumer.signal();
		}
		finally
		{
			lock.unlock();
		}
		
	}
	public void get() throws InterruptedException
	{
		lock.lock();
		try
		{
			while(!flag)
				condition_consumer.await();
			System.out.println(Thread.currentThread().getName()+"----消费者----"+this.shopname);
			flag = false;
			condition_producer.signal();
		}
		finally
		{
			lock.unlock();
		}
	}
}

class Producer implements Runnable
{
	private Resource r;
	Producer(Resource r)
	{
		this.r = r;
	}
	public void run()
	{
		try
		{
			while(true)
				r.set("+商品+");
		}
		catch(InterruptedException in)
		{
			
		}
	}
}
class Consumer implements Runnable
{
	private Resource r;
	Consumer(Resource r)
	{
		this.r = r;
	}
	public void run()
	{
		try
		{
			while(true)
				r.get();
		}
		catch(InterruptedException in)
		{
			
		}
	}
}
class ProducerConsumer
{
	public static void main(String[] args) {
		Resource r = new Resource();
		new Thread(new Producer(r)).start();
		new Thread(new Producer(r)).start();
		new Thread(new Consumer(r)).start();
		new Thread(new Consumer(r)).start();
	}
}


---------------------- ASP.Net+Android+IOS开发.Net培训、期待与您交流! ----------------------详细请查看: http://edu.csdn.net
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值