我在编写一个读串口数据的系统,中间有个读取web service数据的部分(红色部分),现在想实现线程等待读取数据部分的结果返回,设定一个时间,超时的话则线程自动结束,请问该怎么改,能否给出详细点的修改的代码部分。谢谢啊!public synchronized void serialEvent(SerialPortEvent event) {
char[] buffer = new char[200];
readThread = new Thread(this);
readThread.start();
try {
inputStream = serialPort.getInputStream();
reader = new InputStreamReader(inputStream);
reader2= new BufferedReader(reader);
} catch (IOException e) {
}
try {
if(reader2.readLine()!=null)
{
str=reader2.readLine();
String[] array=SubString(str);
JhText.setText(array[0]);
JhmcText.setText(getPara(array[0],"JHconfig.properties"));
JyxxText.setText(array[1]);
if(checkBox.isSelected())
{
serialPort.close();
AxisClient client = new AxisClient();
if(!SSLcheck.isSelected()){
String temp=client.getResult(getPara("url","config.properties"), str);
jyjgText.setText(temp);
} else{
String temp=client.getResult("admina",getPara("url","config.properties"), str);
jyjgText.setText(temp);
}
openPort();
}
}
else{
}
}catch (IOException e) {
}
}
char[] buffer = new char[200];
readThread = new Thread(this);
readThread.start();
try {
inputStream = serialPort.getInputStream();
reader = new InputStreamReader(inputStream);
reader2= new BufferedReader(reader);
} catch (IOException e) {
}
try {
if(reader2.readLine()!=null)
{
str=reader2.readLine();
String[] array=SubString(str);
JhText.setText(array[0]);
JhmcText.setText(getPara(array[0],"JHconfig.properties"));
JyxxText.setText(array[1]);
if(checkBox.isSelected())
{
serialPort.close();
AxisClient client = new AxisClient();
if(!SSLcheck.isSelected()){
String temp=client.getResult(getPara("url","config.properties"), str);
jyjgText.setText(temp);
} else{
String temp=client.getResult("admina",getPara("url","config.properties"), str);
jyjgText.setText(temp);
}
openPort();
}
}
else{
}
}catch (IOException e) {
}
}
主线程进行时间判断,超过一定时间都没有从公共部分读到数据的话,就判断是超时。
可以中止掉那个读数据的线程。
可以用stop函数或者用布尔变量来判断。
setSoTimeout的参数,你找找API,肯定有的。这个用来设置连接超时的,属于底层功能。
/**
* 计时器超时时间
*/
private long timeout;
/**
* 计时是否被取消
*/
private boolean isCanceled = false;
/**
* 当计时器超时时抛出的异常
*/
private TimeoutException timeoutException;
/**
* 构造器
* @param timeout 指定超时的时间
*/
public TimeoutThread(long timeout,TimeoutException timeoutErr) {
super();
this.timeout = timeout;
this.timeoutException = timeoutErr;
//设置本线程为守护线程
this.setDaemon(true);
}
/**
* 取消计时
*/
public void cancel()
{
isCanceled = true;
}
/**
* 启动超时计时器
*/
public void run()
{
try {
Thread.sleep(timeout);
if(!isCanceled)
throw timeoutException;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}对操作进行超时线程结束的操作
try{
readThread.start();
if(checkBox.isSelected())
{
serialPort.close();
AxisClient client = new AxisClient();
if(!SSLcheck.isSelected()){
String temp=client.getResult(getPara("url","config.properties"), str);
jyjgText.setText(temp);
} else{
String temp=client.getResult("admina",getPara("url","config.properties"), str);
jyjgText.setText(temp);
}
readThread.cancel();
}catch(timeoutException e)
{
······结束线程的操作
}
join(time);
或者
用socket 的超时时间