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();
	}

}

猜你喜欢

转载自ontheway-lyl.iteye.com/blog/2259898
今日推荐