java两个线程互相守护

dota打累了写个小demo
最近由于工作需要,需要实现一个线程无论任何情况下都不能挂掉,就算挂掉了也必须继续运行该线程里的功能,想了一下其实也非常简单,无非就是两个线程互相守护,两个线程里实现同样的功能,线程A挂了启动线程B,线程B挂了启动线程A,好了废话不多说,直接上代码:

 

package com.thread.daemon.test;

import java.util.ArrayList;
import java.util.List;


/**
 * 两个线程互相守护,线程A挂了启动线程B,线程B挂了启动线程A
 * @author liangjian
 */
public class ThreadDaemonTest {

	static List<String> list = new ArrayList<>();
	static Thread threadA ;
	static Thread threadB ;
	
	public static void threadDaemonA(){
		threadA = new Thread(new Runnable() {
			boolean flag = true;
			int count = 0;
			@Override
			public void run() {
				threadA.setName("threadDaemonA ");
				while(flag){
					try {
						threadA.sleep(1000);
					} catch (InterruptedException e1) {
						e1.printStackTrace();
						flag = false;
						Thread.currentThread().interrupt();
						threadA = null;
						threadDaemonB();
					}finally{
					}
					count++;
					System.out.println(threadA.getName()+count+ " <--> threadB = "+threadB);
					if(count == 10){
						System.err.println(count);
						try {
							String temp = list.get(0);
						} catch (Exception e) {
							e.printStackTrace();
							threadDaemonB();
							flag = false;
							Thread.currentThread().interrupt();
							threadA = null;
							return;
						}finally{
						}
					}
				}
			}
		});
		threadA.start();
	}
	public static void threadDaemonB(){
		threadB = new Thread(new Runnable() {
			boolean flag = true;
			int count = 0;
			@Override
			public void run() {
				threadB.setName("threadDaemonB ");
				while(flag){
					try {
						threadB.sleep(1000);
					} catch (InterruptedException e1) {
						e1.printStackTrace();
						flag = false;
						Thread.currentThread().interrupt();
						threadB = null;
						threadDaemonA();
					}
					count++;
					System.out.println(threadB.getName()+count+" <--> threadA = "+threadA);
					if(count == 10){
						
						try {
							String temp = list.get(0);
							return ;
						} catch (Exception e) {
							e.printStackTrace();
							flag = false;
							threadB = null;
							Thread.currentThread().interrupt();
							threadDaemonA();
						}finally{
						}
					}
				}
			}
		});
		threadB.start();
	}
	
	public static void main(String[] args) {
		threadDaemonA();
	}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值