参考资料:java线程与并发编程实践
线程状态
NEW:该状态下线程还没有执行
RUNNABLE:该状态下线程正在JVM中执行
BLOCKED:该状态下线程阻塞并等待一个监听锁
WAITING:该状态下线程无限期等待
TIMED_WAITING:该状态下线程在指定时间内等待
TERMINATED:改状态下线程已退出
线程的睡眠和中断
/**
* 线程的睡眠和中断
*/
public class ThreadDemoSleep {
public static void main(String[] args) {
Runnable r = () -> {
String name = Thread.currentThread().getName();
int count = 0;
while (!Thread.interrupted()) {
System.out.println(name + ": " + count++);
}
};
Thread thdA = new Thread(r, "thdA");
Thread thdB = new Thread(r, "thdB");
thdA.start();
thdB.start();
try {
// 睡眠
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 中断
thdA.interrupt();
thdB.interrupt();
}
}
线程等待
package com.scott.current;
import java.math.BigDecimal;
public class ThreadDemoJoin {
private static BigDecimal result;
private static final BigDecimal FOUR = BigDecimal.valueOf(4);
private static final int roundingMode = BigDecimal.ROUND_HALF_EVEN;
public static void main(String[] args) {
Runnable r = () -> {
result = computePi(50000);
};
Thread t = new Thread(r);
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(result);
}
public static BigDecimal computePi(int digits) {
int scale = digits + 5;
BigDecimal arctan1_5 = arctan(5, scale);
BigDecimal arctan1_239 = arctan(239, scale);
BigDecimal pi = arctan1_5.multiply(FOUR).subtract(arctan1_239).multiply(FOUR);
return pi.setScale(digits, BigDecimal.ROUND_HALF_UP);
}
public static BigDecimal arctan(int inverseX, int scale) {
BigDecimal result, numer, term;
BigDecimal invX = BigDecimal.valueOf(inverseX);
BigDecimal invX2 = BigDecimal.valueOf(inverseX * inverseX);
numer = BigDecimal.ONE.divide(invX, scale, roundingMode);
result = numer;
int i = 1;
do {
numer = numer.divide(invX2, scale, roundingMode);
int denom = 2 * i + 1;
term = numer.divide(BigDecimal.valueOf(denom), scale, roundingMode);
if ((i % 2) != 0) {
result = result.subtract(term);
} else {
result = result.add(term);
}
} while (term.compareTo(BigDecimal.ZERO) != 0);
return result;
}
}