灌木大叔

每一个不曾起舞的日子都是对以往生命的辜负!!

  :: 首页 :: :: 联系 :: 订阅 :: 管理 ::

java无主窗口GUI程序主线程不能调用sleep(long)方法,会产生异常。

public class fxframe{

public static void main(String[] args) {

// TODO Auto-generated method stub

fxframe mainframe=new fxframe();

mainframe.go();

}

public void go()

{

buf1=new byte[5000];

running = true;

new Thread() {  

public void run()

{  

  readthread();

};  

}.start(); 

netwatch();

}

netwatch()

{

System.out.println("sendthread starts!");

while (running)

{

if (socket == null)

{

netcon("xx.xx.xx", nport);

}

if (socket != null)

{

try

{

os.write(netreq);

os.flush();

System.out.println("send data!");

}

catch (Exception e)

{

   socket = null;

}

}

 try

{

Thread.sleep(5000);

}

catch (InterruptedException e)

{}

}

try

{

is.close();

os.close();

socket.close();

}

catch (Exception e)

{}

System.out.println("sendthread end!");

}


private void readthread()

{

int i;

String s1;

System.out.println("readthread starts!");

while (running) {

if (socket != null) {

try {

// 读取数据

i=is.read(buf1);

s1=new String(buf1,0,i,"GBK");

System.out.println("recv data!"+s1);

}

catch (IOException e) {

}

} else {

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

}

}

}

System.out.println("readthread end!");

}

}

在这个程序输出JAR,用launch4j.exe包装成exe,运行时在网络监控看到连续不断的发送请求包。其实就是休眠sleep(long)产生异常所致,立即被捕捉又返回循环。

将以上程序的netwatch()启动线程,在主线程调用readthread()后正常。

public void go()

{

buf1=new byte[5000];

running = true;

new Thread() {  

public void run()

{  

netwatch();

};  

}.start(); 

 readthread();

}

posted on 2015-04-07 14:02  灌木大叔  阅读(243)  评论(0)    收藏  举报