java两个线程互相守护
2015-11-28 02:04
337 查看
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(); } }
相关文章推荐
- Java中的守护线程 & 非守护线程(简介)
- Java的守护线程和非守护线程
- JAVA守护线程
- Java多线程通信之两个线程分别打印AB各10次
- Java创建线程的两个方法
- Java 一个简单的线程定时 (守护线程)
- Java创建线程的两个方法
- java的守护线程与非守护线程
- [原]Java多线程编程学习笔记之三:守护线程与线程阻塞的四种情况
- java 多线程:开两个线程,一个线程跑同步代码块,一个线程跑同步函数
- java面试笔试题:设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1.写出程序
- Java创建线程的两个方法
- Java多线程系列--“基础篇”10之 线程优先级和守护线程
- Java DaemonThread(守护线程)
- java的守护线程与非守护线程
- Exchanger——Java两个线程间交换数据的工具类
- Java创建线程的两个方法
- java的守护线程
- JAVA基础(2) -- 两个线程轮流打印1-100
- java学习——使用Exchanger实现两个线程间的数据交换