【发布时间】:2017-02-14 19:40:51
【问题描述】:
所以我尝试每 3 秒发送一次数据包,并尝试使用 Schedule Executor 服务,如下所示:
ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
exec.scheduleWithFixedDelay(new broadcast(), 0, 3, TimeUnit.SECONDS);
但是,为了能够发送数据包,需要抛出异常。我正在努力寻找一种能够抛出此异常的方法。我尝试将其封装在 try, catch 语句中,但没有成功。
static class broadcast implements Runnable{
public void run() {
Iterator iterator = hash.keySet().iterator();
while(iterator.hasNext()){
char c = iterator.next().toString().charAt(0);
int[] a = hash.get(c);
int sendPort = a[1];
byte[] buffer = new byte[1024];
buffer = linkState.toString().getBytes();
System.out.println(a[0] + " " + a[1]);
DatagramPacket sent = new DatagramPacket(buffer, buffer.length, sendAddress, sendPort);
send(sent); //this line here is the problem
}
}
}
private static void send(DatagramPacket sent) throws Exception{
socket.send(sent);
}
感谢您的帮助。
【问题讨论】:
-
@BorisShchegolev 这会使程序进入睡眠状态,我需要它在后台运行。
-
接受的答案是关于
Thread.UncaughtExceptionHandler的使用,而不是关于sleep。
标签: java exception runnable packet datagram