class ShareObject {
private int message = 1;
public synchronized void print() throws InterruptedException {
// Thread.sleep(3000);
System.out.println(Thread.currentThread().getName());
wait();
System.out.println(Thread.currentThread().getName() + message);
}
public void notifyOne() {
notify();
}
}
上面这个是共享类,模拟共享变量。
下面这个是线程类,访问共享变量。
class T implements Runnable {
ShareObject so;
public T(ShareObject so) {
this.so = so;
}
@Override
public void run() {
try {
so.print();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
下面这个是main,测试用的
public class WaitTest {
public static void main(String[] args) throws InterruptedException {
ShareObject so = new ShareObject();
new Thread(new T(so)).start();
new Thread(new T(so)).start();
new Thread(new T(so)).start();
System.out.println("main");
ThreadGroup t = Thread.currentThread().getThreadGroup();
while(t.activeCount()>1)
{
System.out.println(t.activeCount());
Thread.sleep(5000);
so.notifyOne();
}
System.out.println(t.activeCount());
// notifyAll();
// so.notify(); //随机唤醒一条线程
}
}
wait和notify只有拥有锁的线程才有资格调用,这个例子中,3个线程去访问同1个对象so的同步方法so,第一个对象进去后,发现有wait,那么它
就去等(同时释放锁,让第二个线程进来),第二个对象进去后,也发现有wait,它也去等。。。,3个线程启动完后,回到住线程,
///主线程要唤醒刚才那三个wait的线程啊,所以主线程必须要获得so的锁,才能调用notify命令,所以主线程也就so.notifyOne方法,该方法也是同步方法,所以能获得锁