一、线程间通讯
其实就是多个线程在操作同一个资源,但是操作的动作不同。
- 例如有一个资源,包含name sex信息
- 一个输入线程要对其进行赋值
- 一个输出线程要对其进行打印
- 发现用两个线程来分别执行input(存姓名,性别)和output(取姓名,性别)时,会出现安全问题,出现人妖
- 那么让两个线程的动作同步(synchronized)来解决,都加同一把锁(object),这样在某一刻时间,就只能有一个线程能操作资源,貌似解决了问题
- 但是又发现,不能达到输入一个就输出一个,而是成片的输入,成片的输出
- 这时,就考虑加个判断flag,
- 当flag为false代表资源为空可以输入数据,
- 输入完数据后,唤醒output,让flag=true,然后让input wait 释放资源和锁,并等待,
- output输出数据,完成后让flag=false,唤醒input,output wait释放资源和锁。。。。。。
- 这就是多线程的等待唤醒机制
public class Object
{
//1、唤醒在此对象监视器上等待的单个线程。对象监视器相当于锁
public final native void notify();
//2、唤醒在此对象监视器上等待的所有线程。
public final native void notifyAll();
//3、在其他线程调用此对象的 notify() 方法或 notifyAll() 方法前,导致当前线程等待。
public final void wait() throws InterruptedException
{
wait(0);
}
//在其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者超过指定的时间量前,导致当前线程等待。
public final native void wait(long timeout) throws InterruptedException;
}
这三种方法都定义在Object类中,为什么呢?
- 这些方法全用在同步中(因为要对持有监视器《锁》的线程操作,所以要使用在同步中,因为只有同步才具有锁)
- 使用这些方法必须要标识所属的同步的锁=》obj.wait(); obj.notify(); obj.notifyall();
- 也可以说:这些方法在操作同步中线程时,都必须要标识它们所操作线程持有的锁:也就是说等待和唤醒必须是同一个锁
- 锁可以是任意对象,所以任意对象调用的方法一定定义在Object类中
//资源类
class Res
{
String name;
int age;
//因为要先输入,所以初始化为false
boolean flag = false;
//设置资源信息
public synchronized void setRes(String name,int age)
{
if(flag)
try{wait();}catch(Exception e){}
this.name = name;
this.age = age;
flag = true;
notify();
}
//打印资源信息
public synchronized void out()
{
if(!flag)
try{wait();}catch(Exception e){}
System.out.println(name+"----"+age);
flag = false;
notify();
}
}
//输入
class Input implements Runnable
{
Res res = new Res();
Input(Res res)
{
this.res = res;
}
boolean flag = true;
public void run()
{
while(true)
{
if(flag)
{
res.setRes("java",20);
}
else
{
res.setRes("丽丽",18);
}
flag = !flag;
}
}
}
//输出
class Output implements Runnable
{
Res res = new Res();
Output(Res res)
{
this.res = res;
}
public void run()
{
while(true)
{
res.out();
}
}
}
//测试
class Test
{
public static void main(String[] args)
{
Res res = new Res();
Input in = new Input(res);
Output out = new Output(res);
new Thread(in).start();
new Thread(out).start();
new Thread(in).start();
new Thread(out).start();
}
}
四、wait() 和sleep() 的区别:
- wait():释放资源,释放锁,是锁的方法
- sleep():释放资源,不释放锁,是Thread的方法
- wait:可以指定时间也可以不指定时间。不指定时间,只能由对应的notify或者notifyAll来唤醒。
- sleep:必须指定时间,时间到自动从冻结状态转成运行状态(临时阻塞状态)。
class ProducerConsumerDemo
{
public static void main(String[] args)
{
Resource res = new Resource();
Producer pro = new Producer(res);
ConsumerDemo con = new ConsumerDemo(res);
new Thread(pro).start();
new Thread(pro).start();
new Thread(con).start();
new Thread(con).start();
}
}
class Resource
{
String name;
int count = 0;
boolean flag = false;
public synchronized void setRes(String name)
{
while(flag)
try{wait();}catch(Exception e){}
this.name = name + "---" + count++;
System.out.println(Thread.currentThread().getName()+"---生产:"+this.name);
flag = true;
notifyAll();
}
public synchronized void out()
{
while(!flag)
try{wait();}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"--------------消费:"+name);
flag = false;
notifyAll();
}
}
class Producer implements Runnable
{
Resource res = new Resource();
Producer(Resource res)
{
this.res = res;
}
public void run()
{
while(true)
res.setRes("商品");
}
}
class ConsumerDemo implements Runnable
{
Resource res = new Resource();
ConsumerDemo(Resource res)
{
this.res = res;
}
public void run()
{
while(true)
res.out();
}
}
六、jdk1.5升级版的生产者消费者示例
//java.util.concurrent.locks.Lock
class interface Lock
{
//1,获取锁
void lock();
//2,释放锁。
void unlock();
//3,返回绑定到此 Lock 实例的新 Condition 实例
Condition newCondition();
}
- 锁是控制多个线程对共享资源进行访问的工具。
- Lock 实现提供了比使用 synchronized 方法和语句可获得的更广泛的锁定操作。
- 此实现允许更灵活的结构,可以具有差别很大的属性,可以支持多个相关的 Condition 对象。
//一个可重入的互斥锁 Lock,它具有与使用 synchronized 方法和语句所访问的隐式监视器锁相同的一些基本行为和语义,但功能更强大。
//ReentrantLock 将由最近成功获得锁,并且还没有释放该锁的线程所拥有。
//当锁没有被另一个线程所拥有时,调用 lock 的线程将成功获取该锁并返回。
public class ReentrantLock implements Lock, java.io.Serializable
{
private static final long serialVersionUID = 7373984872572414699L;
//构造方法:创建一个 ReentrantLock 的实例。
public ReentrantLock() {
sync = new NonfairSync();
}
//构造方法:创建一个具有给定公平策略的 ReentrantLock。
public ReentrantLock(boolean fair) {
sync = (fair)? new FairSync() : new NonfairSync();
}
//方法主要用到Lock的lock()和unlock();
}
//java.util.concurrent.locks.Condition
//Condition 将 Object 监视器方法(wait、notify 和 notifyAll)分解成截然不同的对象,
//以便通过将这些对象与任意 Lock 实现组合使用,为每个对象提供多个等待 set(wait-set)。
//其中,Lock 替代了 synchronized 方法和语句的使用,Condition 替代了 Object 监视器方法的使用
//Condition 实例实质上被绑定到一个锁上。要为特定 Lock 实例获得 Condition 实例,请使用其 newCondition() 方法。
public interface Condition
{
//造成当前线程在接到信号或被中断之前一直处于等待状态。
void await() throws InterruptedException;
//造成当前线程在接到信号、被中断或到达指定等待时间之前一直处于等待状态
boolean await(long time, TimeUnit unit) throws InterruptedException;
//唤醒一个等待线程。
void signal();
//唤醒所有等待线程。
void signalAll();
}
import java.util.concurrent.locks.*;
class ProducerConsumerDemo1
{
public static void main(String[] args)
{
Resource res = new Resource();
Producer pro = new Producer(res);
ConsumerDemo con = new ConsumerDemo(res);
new Thread(pro).start();
new Thread(pro).start();
new Thread(con).start();
new Thread(con).start();
}
}
class Resource
{
private String name;
private int count = 0;
private boolean flag = false;
Lock lock = new ReentrantLock();
Condition condition_pro = lock.newCondition();
Condition condition_con = lock.newCondition();
public void setRes(String name)throws InterruptedException
{
lock.lock();
try
{
while(flag)
condition_pro.await();
this.name = name + "---" + count++;
System.out.println(Thread.currentThread().getName()+"---生产:"+this.name);
flag = true;
condition_con.signal();
}
finally
{
lock.unlock();
}
}
public void out()throws InterruptedException
{
lock.lock();
try
{
while(!flag)
condition_con.await();
System.out.println(Thread.currentThread().getName()+"--------------消费:"+name);
flag = false;
condition_pro.signal();
}
finally
{
lock.unlock();
}
}
}
class Producer implements Runnable
{
Resource res = new Resource();
Producer(Resource res)
{
this.res = res;
}
public void run()
{
try
{
while(true)
res.setRes("商品");
}
catch (InterruptedException e)
{
}
}
}
class ConsumerDemo implements Runnable
{
Resource res = new Resource();
ConsumerDemo(Resource res)
{
this.res = res;
}
public void run()
{
try
{
while(true)
res.out();
}
catch (InterruptedException e)
{
}
}
}
- JDK1.5中提供了多线程升级解决方案
- 将同步Synchronized替换成Lock
- 将Object中的wait,notify,notifyAll,替换成了Condition对象,该对象可以通过Lock锁获取
- 该示例中实现了本方只唤醒对方的操作
只有一种方法,让run方法结束。
- 定义循环结束标记:因为多线程运行代码一般都是循环,只要控制了循环即可让run方法结束,也就是线程结束
- 如果线程处于了冻结状态,是不可能读到标记的,使用Thread类提供的interrupt方法:该方法是结束线程的冻结状态,让线程回到运行状态中来
-
public class Thread { //注:stop方法已经过时不再使用 //如果线程在调用 Object 类的 wait()方法,或者该类的 join(),sleep(long) 等方法过程中受阻, //则其中断状态将被清除,wait等方法会抛出一个 InterruptedException异常,那么在catch块中可以更改标记结束循环 public void interrupt() {} }