两种方法,一个用标记变量,另一个用语法
不多说,直接代码:
主方法一:
send s = new send();
s.start();
receive r = new receive();
r.start();
class send extends Thread {
public void run() {
//睡眠计数
int s = 0;
//重发计数
int r = 0;
while (flag == true && r < 3) {
try {
if (s == 20) {
// 发送信息
byteout = new PrintStream(socket.getOutputStream());
byteout.write(sendStart.data);
}
s++;
System.out.println(s);
sleep(500);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (r == 3) {
ShowDialog("服务器无响应");
}
}
}
// 业务主线程,负责接收服务器端的消息
class receive extends Thread {
public void run() {
try {
while (socket.isConnected()) {
in = socket.getInputStream();
in.read(content);
// if (收到数据) {
flag = false;
//这个睡眠是为了给时间让send看到标记变量已改变
sleep(1000);
byteout.close();
socket.close();
。。。。。。。。。。。。。。。
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
第二种方法:
package com.test; public class sendto { /** * @param args */ public static void main(String[] args){ // TODO Auto-generated method stub // 开启发送线程 // 开启重发线程 send s = new send(); s.start(); // 监听服务器的反馈 receive r = new receive(s); r.start(); } } class send extends Thread { //重发计数 int r = 0; public void run() { while (r < 3) { try { System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxx"); r++; sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("1111111111"); } } // 业务主线程,负责接收服务器端的消息 class receive extends Thread { private Thread subThread; public receive(Thread thread) { subThread = thread; } public void run() { // 使SEND线程结束 try { sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } subThread.suspend(); System.out.println("关闭"); } }