【发布时间】:2015-01-10 13:48:00
【问题描述】:
我的 android 应用程序中有一个 Button,它必须在按住它的同时运行连续动作,为此我创建了一个 onTouchListener 来处理此类问题,我的结构是在一段时间内捕获 ACTION_DOWN 事件线程时( true) 循环运行,然后当捕获ACTION_UP 事件时,线程通过wait() 停止以恢复它在按住时再次循环,问题是当尝试执行thread.wait() 时,线程没有进入同步块并且不等待,但它会停止执行该线程中存在的runOnUIThread,并且在我按下任何按钮之后,应用程序崩溃并给我ANR Exception : Input dispatching timed out:
// the thread declaratrion
test = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
// still loops here
value = value + 1;
runOnUiThread(new Runnable() {
public void run() {
// doesn't go here anymore
mTextView.setText(Integer.toString(value));
}
});
// still loops here
synchronized (test) {
try {
Thread.sleep(150);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
// the onTouchListener
case MotionEvent.ACTION_DOWN:
if (!test.isAlive()) {
synchronized (test) {
test.start();
}
} else {
synchronized (test) {
test.notify();
}
}
break;
case MotionEvent.ACTION_UP:
// accepts the action
synchronized (test) {
try {
// doesn't goes here
test.wait(); // doesn't execute
} catch (InterruptedException e) {
e.printStackTrace();
}
}
break;
default:
break;
【问题讨论】:
-
一个投反对票并没有任何帮助行动就离开的幽灵投反对票,这就是我在这里所缺少的:D
标签: java android multithreading synchronized