Android中对象锁的wait()和notify()
基本概念:对象锁synchronized(object){….}用法
在以上的代码块中只能由一个线程执行!!!
wait()、notify()是用在这个代码块当中的。wait()可以使当前线程A马上失去对象锁并且沉睡,直到对象调用notify()唤醒该线程。此时持有对象锁的线程B会先行执行完毕,然后再将对象锁交给线程A继续执行。
例子说明:
public classPerson {privateString name;private intage;public Person(String name, intage) {this.name =name;this.age =age;
}publicString getName() {returnname;
}public voidsetName(String name) {this.name =name;
}public intgetAge() {returnage;
}public void setAge(intage) {this.age =age;
}
首先创建一个供线程竞争的Person类,含有构造方法和get、set方法。
final Person person = new Person("王龙",23);
Thread t1= new Thread(newRunnable() {
@Overridepublic voidrun() {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(newRunnable() {
@Overridepublic voidrun() {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/王龙: 观自在菩萨,行深般若波若蜜多时001-13 15:45:19.335 15435-15906/com.huaxinzhi.usingthreadpool E/王龙: 观自在菩萨,行深般若波若蜜多时101-13 15:45:20.335 15435-15906/com.huaxinzhi.usingthreadpool E/王龙: 观自在菩萨,行深般若波若蜜多时201-13 15:45:21.335 15435-15906/com.huaxinzhi.usingthreadpool E/王龙: 观自在菩萨,行深般若波若蜜多时301-13 15:45:22.335 15435-15906/com.huaxinzhi.usingthreadpool E/王龙: 观自在菩萨,行深般若波若蜜多时401-13 15:45:23.335 15435-15906/com.huaxinzhi.usingthreadpool E/王龙: 观自在菩萨,行深般若波若蜜多时501-13 15:45:24.335 15435-15907/com.huaxinzhi.usingthreadpool E/王龙: 照见五蕴皆空,度一切苦厄001-13 15:45:25.335 15435-15907/com.huaxinzhi.usingthreadpool E/王龙: 照见五蕴皆空,度一切苦厄101-13 15:45:26.335 15435-15907/com.huaxinzhi.usingthreadpool E/王龙: 照见五蕴皆空,度一切苦厄201-13 15:45:27.335 15435-15907/com.huaxinzhi.usingthreadpool E/王龙: 照见五蕴皆空,度一切苦厄301-13 15:45:28.335 15435-15907/com.huaxinzhi.usingthreadpool E/王龙: 照见五蕴皆空,度一切苦厄401-13 15:45:29.335 15435-15907/com.huaxinzhi.usingthreadpool E/王龙: 照见五蕴皆空,度一切苦厄501-13 15:45:30.335 15435-15907/com.huaxinzhi.usingthreadpool E/王龙: 照见五蕴皆空,度一切苦厄601-13 15:45:31.335 15435-15907/com.huaxinzhi.usingthreadpool E/王龙: 照见五蕴皆空,度一切苦厄701-13 15:45:32.335 15435-15907/com.huaxinzhi.usingthreadpool E/王龙: 照见五蕴皆空,度一切苦厄801-13 15:45:33.335 15435-15907/com.huaxinzhi.usingthreadpool E/王龙: 照见五蕴皆空,度一切苦厄901-13 15:45:34.335 15435-15906/com.huaxinzhi.usingthreadpool E/王龙: 观自在菩萨,行深般若波若蜜多时601-13 15:45:35.345 15435-15906/com.huaxinzhi.usingthreadpool E/王龙: 观自在菩萨,行深般若波若蜜多时701-13 15:45:36.345 15435-15906/com.huaxinzhi.usingthreadpool E/王龙: 观自在菩萨,行深般若波若蜜多时801-13 15:45:37.345 15435-15906/com.huaxinzhi.usingthreadpool E/王龙: 观自在菩萨,行深般若波若蜜多时9