在以上的代码块中只能由一个线程执行!!! wait()、notify()是用在这个代码块当中的。wait()可以使当前线程A马上失去对象锁并且沉睡,直到对象调用notify()唤醒该线程。此时持有对象锁的线程B会先行执行完毕,然后再将对象锁交给线程A继续执行。 例子说明:
public class Person { private String name; private int age;
public Person(String name, int age) { this.name = name; this.age = age; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; } 首先创建一个供线程竞争的Person类,含有构造方法和get、set方法。
final Person person = new Person("王龙",23); Thread t1 = new Thread(new Runnable() { @Override public void run() { synchronized (person){ try { for (int i = 0 ; i<10 ; i++) { Thread.sleep(1000); Log.e(person.getName(),"观自在菩萨,行深般若波若蜜多时"+i); if (i==5){ person.wait(); } } } catch (InterruptedException e) { e.printStackTrace(); } } } },"Thread1"); Thread t2 = new Thread(new Runnable() { @Override public void run() { synchronized (person){ try { for ( int i = 0 ; i < 10 ; i++ ){ Thread.sleep(1000); Log.e(person.getName(),"照见五蕴皆空,度一切苦厄"+i); if (i==5){ person.notify(); } } } catch (InterruptedException e) { e.printStackTrace(); }
} } },"Thread2"); t1.start(); t2.start(); 线程A和线程B是并发执行的。线程A每隔1s打印一条日志。当循环到第5次的是否wait()放弃对象锁并沉睡。此时线程B获得对象锁开始执行。执行到第5次循环。notify()唤醒线程A。
执行结果:
01-13 15:45:18.335 15435-15906/com.huaxinzhi.usingthreadpool E/王龙: 观自在菩萨,行深般若波若蜜多时0 01-13 15:45:19.335 15435-15906/com.huaxinzhi.usingthreadpool E/王龙: 观自在菩萨,行深般若波若蜜多时1 01-13 15:45:20.335 15435-15906/com.huaxinzhi.usingthreadpool E/王龙: 观自在菩萨,行深般若波若蜜多时2 01-13 15:45:21.335 15435-15906/com.huaxinzhi.usingthreadpool E/王龙: 观自在菩萨,行深般若波若蜜多时3 01-13 15:45:22.335 15435-15906/com.huaxinzhi.usingthreadpool E/王龙: 观自在菩萨,行深般若波若蜜多时4 01-13 15:45:23.335 15435-15906/com.huaxinzhi.usingthreadpool E/王龙: 观自在菩萨,行深般若波若蜜多时5 01-13 15:45:24.335 15435-15907/com.huaxinzhi.usingthreadpool E/王龙: 照见五蕴皆空,度一切苦厄0 01-13 15:45:25.335 15435-15907/com.huaxinzhi.usingthreadpool E/王龙: 照见五蕴皆空,度一切苦厄1 01-13 15:45:26.335 15435-15907/com.huaxinzhi.usingthreadpool E/王龙: 照见五蕴皆空,度一切苦厄2 01-13 15:45:27.335 15435-15907/com.huaxinzhi.usingthreadpool E/王龙: 照见五蕴皆空,度一切苦厄3 01-13 15:45:28.335 15435-15907/com.huaxinzhi.usingthreadpool E/王龙: 照见五蕴皆空,度一切苦厄4 01-13 15:45:29.335 15435-15907/com.huaxinzhi.usingthreadpool E/王龙: 照见五蕴皆空,度一切苦厄5 01-13 15:45:30.335 15435-15907/com.huaxinzhi.usingthreadpool E/王龙: 照见五蕴皆空,度一切苦厄6 01-13 15:45:31.335 15435-15907/com.huaxinzhi.usingthreadpool E/王龙: 照见五蕴皆空,度一切苦厄7 01-13 15:45:32.335 15435-15907/com.huaxinzhi.usingthreadpool E/王龙: 照见五蕴皆空,度一切苦厄8 01-13 15:45:33.335 15435-15907/com.huaxinzhi.usingthreadpool E/王龙: 照见五蕴皆空,度一切苦厄9 01-13 15:45:34.335 15435-15906/com.huaxinzhi.usingthreadpool E/王龙: 观自在菩萨,行深般若波若蜜多时6 01-13 15:45:35.345 15435-15906/com.huaxinzhi.usingthreadpool E/王龙: 观自在菩萨,行深般若波若蜜多时7 01-13 15:45:36.345 15435-15906/com.huaxinzhi.usingthreadpool E/王龙: 观自在菩萨,行深般若波若蜜多时8 01-13 15:45:37.345 15435-15906/com.huaxinzhi.usingthreadpool E/王龙: 观自在菩萨,行深般若波若蜜多时9