java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at com.……
错误代码:
public static void main(String args[]) { try { // 确定服务地址 URL url = new URL( "http://192.168.1.168:8080/smart/save.do?token=00124B0006234CF50102"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStream out = conn.getOutputStream(); InputStream in = conn.getInputStream(); Object obj = new Object(); int n = -1; byte[] b = new byte[1024]; // 从服务端读取数据并打印 while (true) { if ((n = in.read(b)) != -1) { String s = new String(b, 0, n, "UTF-8"); System.out.println(s); } String content = UUID.randomUUID().toString(); out.write(content.getBytes()); out.flush(); obj.wait(3000); } } catch (Exception e) { e.printStackTrace(); } }错误发生在语句:obj.wait(3000);
为什么会发生这个错误呢?
因为不存在锁,不存在对象争用的情况吧。
解决方法
synchronized (obj) { obj.wait(3000); }加个同步块就可以了。