【Java 线程问题】在 run() 中调用阻塞函数的问题。【解决加分,信誉保证】

Wolf0403 2003-08-26 05:57:28
...
ListenSocket server = new ListenSocket();

private SockPool(){
Thread tServer = new Thread(server, "ListenSocket");
tServer.run();
}

static void main(String[] arg){
new SockPool();
...
这是我的部分代码。tServer.run() 调用了 server.run() 函数,那么这个 server.run() 是在主线程中运行的吗?如果是,那么应该怎么写才对?如果不是,我的 ListenSocket.run() 方法中有阻塞 IO 函数,结果导致 main 中 new SockPool() 之后的代码无法执行,请问怎么解决?
谢谢。
...全文
148 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Wolf0403 2003-08-29
  • 打赏
  • 举报
回复
谢谢!几天以来一直没法上网,今天刚刚来:)
storm999 2003-08-27
  • 打赏
  • 举报
回复
我只是隨便寫一下﹐這樣在做你的小例子時沒問題﹐不過效率不高﹐你自已可以優化一下
storm999 2003-08-27
  • 打赏
  • 举报
回复
對不起﹐昨天太匆忙﹐看錯了。
有錯的地方應是
int length = is.available();
int totalLength = length;

available()總是返回0﹐所以下面的循環總是沒有執行.
你可以這樣寫

Socket sc = s.accept();
InputStream is = sc.getInputStream();
byte[] buffer = new byte[1024];
int chars_read;
String str = "";
while ((chars_read = is.read(buffer)) != -1 ) {
str += new String(buffer,0,chars_read);
}
System.out.println("Got string: " + str);
storm999 2003-08-26
  • 打赏
  • 举报
回复
run()方法只是調用了一個函數﹐而沒有啟動線程﹐要啟動線程﹐不要用run(),而是要用start()方法
storm999 2003-08-26
  • 打赏
  • 举报
回复
我有急事﹐馬上要走了﹐不過看了你的程序﹐有一個地方好像有問題
for (;length != 0; length -= 128){ // Keeps reading until the end;
byte c[] = new byte[128];
。。。

c[]每次循環都重新創建﹐得到的值應不對﹐

不過沒有仔細看﹐明天再給看一下﹐我走了
Wolf0403 2003-08-26
  • 打赏
  • 举报
回复
谢谢飞鱼指点!再一个进一步的问题 :D 搞定了结帖
我的 tServer.start() 调用的函数如下:
void Listen(){
try{
s = new ServerSocket(3000, 20);
while (true){ // Keeps fetching data
sc = s.accept();
is = sc.getInputStream();
int length = is.available();
int totalLength = length;
for (;length != 0; length -= 128){ // Keeps reading until the end;
byte c[] = new byte[128];
try{
is.read(c, totalLength - length, 128);
}
catch (IOException ioex){
System.err.println("IO error occured while getting data from socket");
}
finally{
str += new String(c);
}
}
// Callback function here to return the string
System.out.println("Got string: " + str);
}
}
catch (IOException ioex){
System.err.println("Server Socket Creation Failed!");
}
}
随后在另外一线程启动如下函数
try{
s = new java.net.Socket(this.remoteAddress, this.remotePort);
OutputStream os = s.getOutputStream();
os.write(str.getBytes());
}
catch (IOException ioex){
System.err.println("Failed to init socket to send data");
}
为什么最后打印出来只有 Got string: 后面空白?谢谢!

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧