我的代码如下:
public class Imagechanger extends AsyncTask<Object,Void,Void >{
@Override
protected Void doInBackground(Object... params) {
if(!isCancelled()){
final ImageView v = (ImageView)params[0];
final Context c = (Context)params[1];
while(true){
try {
this.wait(4*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(c.getResources().getDrawable(R.drawable.banner1).equals(v.getBackground()))
v.setImageDrawable(c.getResources().getDrawable(R.drawable.banner2));
else
v.setImageDrawable(c.getResources().getDrawable(R.drawable.banner1));
}
}
return null;
}
}
上面的代码抛出了以下异常:
04-26 12:24:06.563: ERROR/AndroidRuntime(6332): java.lang.RuntimeException: An error occured while executing doInBackground()
04-26 12:24:06.563: ERROR/AndroidRuntime(6332): at android.os.AsyncTask$3.done(AsyncTask.java:200)
04-26 12:24:06.563: ERROR/AndroidRuntime(6332): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
04-26 12:24:06.563: ERROR/AndroidRuntime(6332): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
04-26 12:24:06.563: ERROR/AndroidRuntime(6332): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
04-26 12:24:06.563: ERROR/AndroidRuntime(6332): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-26 12:24:06.563: ERROR/AndroidRuntime(6332): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
04-26 12:24:06.563: ERROR/AndroidRuntime(6332): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
04-26 12:24:06.563: ERROR/AndroidRuntime(6332): at java.lang.Thread.run(Thread.java:1096)
04-26 12:24:06.563: ERROR/AndroidRuntime(6332): Caused by: java.lang.IllegalMonitorStateException: object not locked by thread before wait()
04-26 12:24:06.563: ERROR/AndroidRuntime(6332): at java.lang.Object.wait(Native Method)
04-26 12:24:06.563: ERROR/AndroidRuntime(6332): at java.lang.Object.wait(Object.java:326)
04-26 12:24:06.563: ERROR/AndroidRuntime(6332): at com.helios.NauticDates.SimpleCalendarViewActivity$Imagechanger.doInBackground(SimpleCalendarViewActivity.java:525)
04-26 12:24:06.563: ERROR/AndroidRuntime(6332): at com.helios.NauticDates.SimpleCalendarViewActivity$Imagechanger.doInBackground(SimpleCalendarViewActivity.java:1)
04-26 12:24:06.563: ERROR/AndroidRuntime(6332): at android.os.AsyncTask$2.call(AsyncTask.java:185)
04-26 12:24:06.563: ERROR/AndroidRuntime(6332): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
04-26 12:24:06.563: ERROR/AndroidRuntime(6332): ... 4 more
怎么了?我听不懂。第525行是带有等待指令的行。
提前感谢。
这里你试图在对象上调用wait()
方法,这里你需要保持该对象上的同步锁
try { synchronized (this) {
this.wait();}
} catch (InterruptedException e) {
e.printStackTrace();
}