线程1负责将初始值每次加1,直到100,在每次累加过程中,如果结果是10的倍数,通知线程2打印。
class M {
private int num = 1;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
class CalThread implements Runnable {
private M m;
public CalThread(M m) {
this.m = m;
}
@Override
public void run() {
synchronized (m) {
while (m.getNum() < 100) {
int t = m.getNum() + 1;
m.setNum(t);
if (t % 10 == 0) {
m.notifyAll();
try {
m.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class PrintThread implements Runnable {
private M m;
public PrintThread(M m) {
this.m = m;
}
@Override
public void run() {
synchronized (m) {
try {
while (!Thread.interrupted()) {
// m.wait();
System.out.println(m.getNum());
m.notifyAll();
if(m.getNum()==100)
return;
m.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyThread {
public static void main(String[] args) {
M m = new M();
Thread t1 = new Thread(new CalThread(m));
Thread t2 = new Thread(new PrintThread(m));
t1.start();
t2.start();
}
}
输出结果:
10
20
30
40
50
60
70
80
90
100
(1)虽然线程的执行具有不确定性,但程序执行依然是按顺序执行,如果取消了打印线程中的注释,打印线程就会一直处于挂起状态;
(2)开始运行时,程序一直抛出java.lang.IllegalMonitorStateException 异常,原因是没按规则使用wait,notify,notifyAll等方法。
=================================================================
void notify()
唤醒在此对象监视器上等待的单个线程。
void notifyAll()
唤醒在此对象监视器上等待的所有线程。
void wait()
导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法。
唤醒在此对象监视器上等待的单个线程。
void notifyAll()
唤醒在此对象监视器上等待的所有线程。
void wait()
导致当前的线程等待,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法。
根据jdk的void notifyAll()的描述,“解除那些在该对象上调用wait()方法的线程的阻塞状态。该方法只能在同步方法或同步块内部调用。如果当前线程不是对象所得持有者,该方法抛出一个
java.lang.IllegalMonitorStateException 异常”
参考:http://blog.csdn.net/intlgj/article/details/6245226