Java Android线程错误
我实际上正在开发一个android聊天应用程序 我创建的线程有问题。基本上,我的客户端应用程序有一个连接到服务的活动。该服务负责客户端和服务器之间的通信。(我也为此使用Asynctask) 我有两个主要场景:Java Android线程错误,java,android,multithreading,android-asynctask,Java,Android,Multithreading,Android Asynctask,我实际上正在开发一个android聊天应用程序 我创建的线程有问题。基本上,我的客户端应用程序有一个连接到服务的活动。该服务负责客户端和服务器之间的通信。(我也为此使用Asynctask) 我有两个主要场景: 我向服务器发送了一个请求(刷新好友列表、添加好友、登录…),服务器的响应是预期的,因此没有问题 第二个场景是关于来自服务器的意外请求(当其他人想要与您通信时)。为此,我在我的服务类中创建了一个线程,如下所示 public void launchListener(){ 问题是,该线程只
- 我向服务器发送了一个请求(刷新好友列表、添加好友、登录…),服务器的响应是预期的,因此没有问题
- 第二个场景是关于来自服务器的意外请求(当其他人想要与您通信时)。为此,我在我的服务类中创建了一个线程,如下所示 public void launchListener(){
protected String doInBackground(String... message) {
this.message = message[0];
this.out = service.getOut();
this.in = service.getIn();
try {
this.out.writeBytes(this.message + "\n");
this.out.flush();
} catch (IOException e) {
e.printStackTrace();
}
response = readLine(this.in);
return response;
}
我真的不知道为什么它不工作,可能asynctask readLine先读取响应,然后当我的线程读取响应时,DataInputStream是空的,它会冻结
无论如何,感谢您的帮助!!如果(in.available()>0){
的计算结果为false
您正在浪费整个CPU内核,如果您在单核设备上运行,您的设备将冻结
要缓解这种情况,请从Thread.sleep
开始,然后进入BlockingQueue
此外,您正在从两个线程访问您的服务,我希望它是线程安全的
while(true){
try {
if (in.available() > 0) {
msg = in.readLine();
msg_parts = msg.split(" ");
if (msg_parts[0].equals("CONNECTION")){
Log.d("SocketService", "Broadcasting message");
Intent intent = new Intent("ask.connection");
intent.putExtra("nickname", msg_parts[1]);
sendBroadcast(intent);
}
} else {
Thread.sleep(100); // Or any sufficient delay.
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
}
根本不需要检查,
BufferedReader.readLine()
(我相信这就是OP正在使用的)无论如何都会被阻止。
while(true){
try {
if (in.available() > 0) {
msg = in.readLine();
msg_parts = msg.split(" ");
if (msg_parts[0].equals("CONNECTION")){
Log.d("SocketService", "Broadcasting message");
Intent intent = new Intent("ask.connection");
intent.putExtra("nickname", msg_parts[1]);
sendBroadcast(intent);
}
} else {
Thread.sleep(100); // Or any sufficient delay.
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
}