this is my piece of code:
// TODO Auto-generated method stub
try
{
Socket clientSocket = new Socket("localhost", 8888);
ObjectOutputStream ous = new ObjectOutputStream(clientSocket.getOutputStream());
while(sending)
{
Statistics statsData = setStatisticsData();
ous.writeObject(statsData);
Thread.sleep(5000);
}
}
catch(UnknownHostException uhe)
{
uhe.printStackTrace();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
it’s the client.it’ll sending in an infinite loop an object Statistics. I would implement a way to break this infinite loop through input (es. press a button in the keyboard).ok can I do?how can i break an infinite loop?
If this is a separate thread:
Then simply interrupt it:
InterruptedExceptionwill be thrown, escaping from the loop.I see you already have a boolean
sendingflag. It will work as well, but with 5 second delay in worst case. Also make sure it isvolatile– or better, useisInterrupted()method of thread. But interrupting the thread usinginterrupt()is by far the easiest way (no extra coding required). And your loop can be truly infinite (although withwhile(true)while(!isInterrupted())).BTW your
setStatisticsData()should probably be namedgetStatisticsData().