不要用while(true)防止主线程退出,会导致cpu占用变高。阿里开源RPC框架dubbo中找到了答案。
https://github.com/apache/dubbo/blob/2d9583adf26a2d8bd6fb646243a9fe80a77e65d5/dubbo-container/dubbo-container-api/src/main/java/org/apache/dubbo/container/Main.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package com.me;
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock;
public class Test {
private static final ReentrantLock LOCK = new ReentrantLock(); private static final Condition STOP = LOCK.newCondition();
public static void main(String[] args) { System.out.println("do not exit"); try { LOCK.lock(); STOP.await(); } catch (InterruptedException e) { System.out.println(e.toString()); } finally { LOCK.unlock(); } } }
|