你的位置:首页 > Java教程

[Java教程][javaSE] 多线程通信(等待


两个线程操作同一个资源,比如,输入和输出,操作同一个对象,此时两个线程会争夺cpu的执行权,随机的进行切换。我们想实现先输入再输出,顺序的执行

 

目标对象定义一个标记字段,进行判断,wait()和notify()方法

wait()方法,线程会处于等待状态,等待的线程位于内存中的线程池中

notify()方法,唤醒线程池中的线程

notifyAll()方法,唤醒全部线程

上面的方法,需要写在同步里面,并且需要标识锁

这些操作线程的方法定义在Object对象中,因为这些方法,要通过同一个锁对象来调用

 

 

/** * 资源 * * @author taoshihan * */class People {  String name;  String sex;  Boolean myLock = false;}/** * 输入 * * @author taoshihan * */class PeopleJoin implements Runnable {  private People resource;  public PeopleJoin(People resource) {    this.resource = resource;  }  @Override  public void run() {    // 切换    boolean flag = true;    while (true) {      synchronized (resource) {        if (resource.myLock) {          try {            resource.wait();          } catch (InterruptedException e) {            e.printStackTrace();          }        }        if (flag) {          resource.name = "taoshihan";          resource.sex = "nan";        } else {          resource.name = "陶士涵";          resource.sex = "男";        }        flag = !flag;        resource.myLock=true;        resource.notify();      }    }  }}/** * 输出 * * @author taoshihan * */class PeopleOut implements Runnable {  private People resource;  public PeopleOut(People resource) {    this.resource = resource;  }  @Override  public void run() {    while (true) {      synchronized (resource) {        if(!resource.myLock){          try {            resource.wait();          } catch (InterruptedException e) {            e.printStackTrace();          }        }        System.out.println(resource.name + "=====" + resource.sex);        resource.myLock=false;        resource.notify();      }    }  }}public class ThreadDemo {  /**   * @param args   */  public static void main(String[] args) {    People resource = new People();    PeopleJoin input = new PeopleJoin(resource);    PeopleOut output = new PeopleOut(resource);    Thread t1 = new Thread(input);    Thread t2 = new Thread(output);    t1.start();    t2.start();  }}