我有一个简单的代码:
private List<String> requests = Collections.synchronizedList(new LinkedList<String>());
和
synchronized (requests) {
((LinkedList<String>)requests).addLast(message);
}
在运行时,我得到这个错误:
FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:2144)
at android.view.View.performClick(View.java:2485)
at android.view.View$PerformClick.run(View.java:9080)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at android.view.View$1.onClick(View.java:2139)
... 11 more
Caused by: java.lang.ClassCastException: java.util.Collections$SynchronizedList
at com.countryst.nabard.turnbased.client.networking.ClientNetworking.login(ClientNetworking.java:72)
at com.countryst.nabard.turnbased.client.MainActivity.loginToServer(MainActivity.java:87)
at com.countryst.nabard.turnbased.client.MainActivity.onButtonClicked(MainActivity.java:217)
... 14 more
这是安卓程序的一部分,我的纯java代码中有类似的代码,运行良好。
synchronizedList
并没有记录它将返回一些可以强制转换回底层列表的内容,只是它返回一些实现List<E>
的同步内容。
如果您需要使用特定于LinkedList
的方法,请参考原始列表:
private LinkedList<String> requestsLinkedList = new LinkedList<String>();
private List<String> requests = Collections.synchronizedList(requestsLinkedList);
然后像这样同步:
synchronized (requests) {
requestsLinkedList.addLast(message);
}
但在这种情况下,您不需要这样做,因为LinkedList#addLast
等效于List#add
。