1.wait方法
This method should only be called by a thread that is the owner
* of this object’s monitor. See the {@code notify} method for a
* description of the ways in which a thread can become the owner of
* a monitor.
(1)该方法仅仅被拥有该对象的监控者的线程调用;
(2)调用后产生的后果是该线程被放到这个对象的wait集合中;放弃关于该对象的任何同步声明;线程变得无法参与调度.
(3)直到其他线程调用该对象的notify等…;该线程才有机会从wait集合中移除,可被再次有机会调度.
2.notify方法
Wakes up a single thread that is waiting on this object’s monitor.
(1)唤醒一个在该对象上等待状态的线程.
(2)该方法仅仅能够在拥有此对象monitor的线程内调用
* This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:
- *
- By executing a synchronized instance method of that object. *
- By executing the body of a {@code synchronized} statement * that synchronizes on the object. *
- For objects of type {@code Class,} by executing a * synchronized static method of that class. *
3.更多参考Object源码中注释
4 . 实例问题
java.lang.IllegalMonitorStateException: object not locked by thread before wait()?
https://stackoverflow.com/questions/26590542/java-lang-illegalmonitorstateexception-object-not-locked-by-thread-before-wait
注意: 当要wait或notify一个对象的时候一定要获得这个对象的锁,即
synchronized (updateThread) {
updateThread.wait(300);
}
自己写的demo:
public String getPhone(final Context context) { // 该方法运行与非主线程
final String[] phone = {null};
runOnUiThread(new Runnable() { // 运行与主线程
@Override
public void run() {
View view = View.inflate(context, R.layout.phone, null);
final EditText phoneView = view.findViewById(R.id.phone);
new AlertDialog.Builder(context)
.setTitle("Input your phone")
.setView(view)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
synchronized (phone) {
phone.notify();
}
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
phone[0] = phoneView.getText().toString();
synchronized (phone) {
phone.notify(); // 主线程,获得phone的lock, 通过notify释放所有等待在phone上的线程; 非主线程可以跑起来了.
}
}
})
.create().show();
}
});
synchronized (phone) {
try {
phone.wait(); // 非主线程中wait, 非主线程失去了对phone的lock,并等待在了phone对象上.
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return phone[0];
}