做java开发多年,一直都没有机会使用wait()和notify(),今天写个例子出来,加深对对象锁的理解: package com.synchronize; import java.util.Date; public class People { private String name; public People(String name) { this.name=name; } public void shop() throws InterruptedException { synchronized (this) { System.out.println(name+" start to shop:" + new Date().toLocaleString()); Thread.currentThread().sleep(2000); System.out.println(name+" end to shop:" + new Date().toLocaleString()); } } public void work() throws InterruptedException { synchronized (this) { System.out.println(name+" start to work:" + new Date().toLocaleString()); Thread.currentThread().sleep(2000); System.out.println(name+" end to work:" + new Date().toLocaleString()); } } public void think() throws InterruptedException { synchronized (this) { System.out.println(name+" start to think:" + new Date().toLocaleString()); this.wait(2000); System.out.println(name+" end to think:" + new Date().toLocaleString()); } } public void talk() throws InterruptedException { synchronized (this) { System.out.println(name+" start to talk:" + new Date().toLocaleString()); this.notify(); Thread.currentThread().sleep(2000); System.out.println(name+" end to talk:" + new Date().toLocaleString()); } } public static void main(String[] args) throws InterruptedException { //test synchronized keyword, run shop() first, then run work(). final People John = new People("John"); Thread t1 = new Thread() { @Override public void run() { try { John.shop(); } catch (InterruptedException e) { e.printStackTrace(); } } }; Thread t2 = new Thread() { @Override public void run() { try { John.work(); } catch (InterruptedException e) { e.printStackTrace(); } } }; t1.start(); Thread.currentThread().sleep(100); t2.start(); //test wait() and notify(), first think(), interrupt by talk(), end to talk, last end to think. final People Mike = new People("Mike"); Thread t3 = new Thread() { @Override public void run() { try { Mike.think(); } catch (InterruptedException e) { e.printStackTrace(); } } }; Thread t4 = new Thread() { @Override public void run() { try { Mike.talk(); } catch (InterruptedException e) { e.printStackTrace(); } } }; t3.start(); Thread.currentThread().sleep(100); t4.start(); } }