版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cckevincyh/article/details/80733815 </div>
<link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-f57960eb32.css">
<div id="content_views" class="markdown_views">
<!-- flowchart 箭头图标 勿删 -->
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;"><path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></path></svg>
<p>在<a href="https://blog.csdn.net/cckevincyh/article/details/80725346" rel="nofollow" target="_blank">Zookeeper的java客户端API</a> 我们了解到Zookeeper客户端里面有Listener这一个线程一直在等待事件触发,既然有一个线程一直在,那么我们应该就不需要在业务线程中写<code>Thread.sleep(Long.MAX_VALUE);</code></p>
我们可以写一个简单的demo来看看:
package cn.itcast.bigdata.zkdist;
public class Test {
public static void main(String[] args) {
System.out.println("主线程开始了");
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程开始了");
while(true){
}
}
});
thread.start();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
我们运行的时候可以发现,这个程序一直没有结束。
所以只要我们有一个线程在,我们的程序就不会停止。那为什么我们在zookeeper的客户端的业务线程还需要Thread.sleep(Long.MAX_VALUE);
让程序不停止。
因为我们zookeeper里面的两个线程connector和listener都是守护线程。zookeeper设计的时候必须把这两个线程设置为守护线程,否则我们业务线程就退不出来了。
我们下面来看看一个守护线程的demo:
package cn.itcast.bigdata.zkdist;
public class Test {
public static void main(String[] args) {
System.out.println("主线程开始了");
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程开始了");
while(true){
}
}
});
//设置为守护线程
thread.setDaemon(true);
thread.start();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
运行后可以发现,程序退出了,启动的线程也退出了。