我在运行java线程时遇到问题,它只能运行一次
我正在设计一个使用套接字的聊天应用程序。这是从服务器读取数据的代码。 它编译得很好,但线程只运行一次。请帮帮我我在运行java线程时遇到问题,它只能运行一次,java,multithreading,sockets,try-catch,Java,Multithreading,Sockets,Try Catch,我正在设计一个使用套接字的聊天应用程序。这是从服务器读取数据的代码。 它编译得很好,但线程只运行一次。请帮帮我 public void reader() { Thread read=new Thread(){ public void run(){ try { while(true) { if(in.readLine()!=null) {
public void reader() {
Thread read=new Thread(){
public void run(){
try {
while(true) {
if(in.readLine()!=null) {
System.out.println("Recived Message: "+ in.readLine());
}
}
}catch(Exception e){}
}
};
read.setPriority(10);
read.start();
}
好的,我试过这个代码,但它不起作用
public void reader()
{
Thread u=new Thread()
{
public void run()
{
try {
while(true)
{
System.out.println("ssss");
if(input.readLine()!=null)
{
String message=input.readLine();
System.out.println("SERVER:"+message);
}
else{
Thread.sleep(1);
}
}
}
catch (IOException e)
e.printStackTrace();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
};
try{
u.start();
}catch(Exception e){}
}
我得到的结果是
sss
就一次。但我有一个始终正确的while循环。为什么ir不能无限运行 (由于声誉低下,无法发表评论…)
最好这样读:
String line = "";
while( (line = in.readLine()) != null) {
System.out.println("Recived Message: " + line);
}
注意,您正在调用2次readLine()您调用readLine两次,每次调用都会获取下一行,因此第一行正在读取该行,而第二行没有任何内容要读取,因此它卡住了您需要做的是删除catch和IOException
如果你不止一次需要一个线程,你应该考虑把它封装在一个类中。 就像这里看到的:
public class Foo extends Thread
{
public Foo()
{
super("Foo");
}
@Override
public void run()
{
while(!isInterrupted())
{
System.out.println("Still running");
try
{
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
Thread foo = new Foo();
foo.start();
}
}
< >否则,您可以考虑实现可运行的接口,因为它被看作是java中处理线程的首选方式。
有关其原因的更多信息,请查看:
希望这能有所帮助。
抓住(例外e){}
-你是故意朝自己的脚开枪。停止这样做。进程仍在控制台中运行,而(true)为什么要每读一行就丢弃一行?添加e.printStackTrace()代码>在您的catch块中查看是否有任何异常。它编译得很好,但while循环只运行一次。我也尝试过这种方法。但是while循环仍然只在readLine刚刚读取1行或之后返回null时运行。也许打印catch块可以给你一些提示:catch(异常e){e.getMessage()}我解决了这个问题。但while循环仍不会运行多次