Java中的线程:如何锁定对象?
2022-09-01 08:02:16
以下函数在其自己的线程中执行:
private void doSendData()
{
try {
//writeToFile(); // just a temporary location of a call
InetAddress serverAddr = InetAddress.getByName(serverAddress);
serverAddr.wait(60000);
//Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr, portNumber);
socket.setSoTimeout(3000);
try {
//Log.d("TCP", "C: Sending: '" + message + "'");
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
String message = packData();
out.println(message);
Log.d("TCP", "C: Sent.");
Log.d("TCP", "C: Done.");
connectionAvailable = true;
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
connectionAvailable = false;
} finally {
socket.close();
announceNetworkAvailability(connectionAvailable);
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
announceNetworkAvailability(connectionAvailable);
}
}
当执行到达该行时,它会引发异常:serverAddr.wait(60000)
java.lang.IllegalMonitorStateException: object not locked by thread before wait()
有谁知道如何锁定对象或函数以防止并发?我尝试添加一个 Lock 对象:
private final Lock lock = new ReentrantLock();
和行
boolean locked = lock.tryLock();
在功能开始时,但它不起作用。