java 一个线程控制另一个线程

两种方法,一个用标记变量,另一个用语法

不多说,直接代码:

主方法一:


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("关闭");

	}
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值