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

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();

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值