wait()和notify()是直接隶属于Object类,也就是说,所有对象都拥有这一对方法。初看起来这十分 不可思议,但是实际上却是很自然的,因为这一对方法阻塞时要释放占用的锁,而锁是任何对象都具有的,调用任意对象的 wait() 方法导致线程阻塞,并且该对象上的锁被释放。而调用任意对象的notify()方法则导致因调用该对象的wait() 方法而阻塞的线程中随机选择的一个解除阻塞(但要等到获得锁后才真正可执行)。
02 * <pre>
03 * 子线程循环10次,接着主线程循环100次,接着有回到子线程循环10次,
04 * 接着再回到主线程循环100次,如此执行50次
05 * </pre>
06 * @author ketqi
07 */
08 public class WaitNotifyDemo {
09 public static void main(String[] args) {
10
11 final Business business = new Business();
12 new Thread(new Runnable() {
13 @Override
14 public void run() {
15 for (int i = 1; i <= 50; i++) {
16 business.sub(i);
17 }
18
19 }
20 }).start();
21
22 for (int i = 1; i <= 50; i++) {
23 business.main(i);
24 }
25 }
26 }
27
28 class Business {
29 private boolean isMainThread = true;
30
31 public synchronized void sub(int i) {
32 while (!isMainThread) {
33 try {
34 this.wait();
35 } catch (InterruptedException e) {
36 e.printStackTrace();
37 }
38 }
39 for (int j = 1; j <= 10; j++) {
40 System.out.println("sub thread sequence of " + j + ",loop of " + i);
41 }
42 isMainThread = false;
43 this.notify();
44 }
45
46 public synchronized void main(int i) {
47 while (isMainThread) {
48 try {
49 this.wait();
50 } catch (InterruptedException e) {
51 e.printStackTrace();
52 }
53 }
54 for (int j = 1; j <= 100; j++) {
55 System.out.println("main thread sequence of " + j + ",loop of " + i);
56 }
57 isMainThread = true;
58 this.notify();
59 }
60 }