【发布时间】:2021-05-30 07:17:39
【问题描述】:
我有两个线程,我们称它们为A 和B。 A 不断通过readPacket 函数从ObjectInputStream 中寻找数据包(这将是while(true) 在线程等中)
当A 正在寻找这些数据包时,我希望B 通过writePacket 函数将数据包写入ObjectOutputStream。
但是每当我想这样做时,我都会陷入僵局;我不明白两个不同的函数怎么会互相死锁?
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.locks.ReentrantLock;
public class ConnectionBay
{
private Socket connection;
private ObjectOutputStream output_stream;
private ObjectInputStream input_stream;
ConnectionBay(Socket socket) throws IOException{
this.connection = socket;
this.output_stream = new ObjectOutputStream(connection.getOutputStream());
this.output_stream.flush();
this.output_stream.reset();
this.input_stream = new ObjectInputStream(connection.getInputStream());
}
public synchronized void writePacket(Packet packet) throws IOException{
this.output_stream.writeObject(packet);
this.output_stream.flush();
this.output_stream.reset();
}
public synchronized Packet readPacket() throws IOException, ClassNotFoundException{
return (Packet)this.input_stream.readObject();
}
}
【问题讨论】:
-
检查你是否遇到过同样的情况:stackoverflow.com/a/14495980/15273968
-
this answer 是否满足您的要求?如果没有,如果您在答案下方发表评论,将会很有帮助。
标签: java multithreading locking