Object类中提供了用于线程通信的方法:wait()和notify(),notifyAll()。如果线程对一个指定的对象x发出一个wait()调用,该线程会暂停执行,此外,调用wait()的线程自动释放对象的锁,直到另一个线程对同一个指定的对象x发出一个notify()调用。
为了让线程对一个对象调用wait()或notify(),线程必须锁定那个特定的对象。也就是说,只能在它们被调用的实例的同步块内使用wait()和notify()。
根据以上内容,修改Person类如下:
package com.itjob;
public class Person {private String name = "王非";private String sex = "女";//为true时,修改数据;为false时,显示数据boolean flag = false;public synchronized void put(String name, String sex){if(flag){try {wait();} catch (InterruptedException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}this.name = name;try {Thread.sleep(100);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}this.sex = sex;flag = true;notifyAll();}public synchronized void get(){if(!flag){try {wait();} catch (InterruptedException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}} System.out.println(name + "----->" + sex);flag = false;notifyAll();}
}