- 线程状态
public enum State {
NEW,
RUNNABLE,
BLOCKED,
WAITING,
TIMED_WAITING,
TERMINATED;
}
- NEW新建
@Test
void testNewState() {
Thread t = new Thread(() -> System.out.println("do something"));
assertEquals(Thread.State.NEW, t.getState());
}
- RUNNABLE运行
@Test
void testRunnableState() {
Thread t = new Thread(() -> {
long startTime = System.currentTimeMillis();
while (System.currentTimeMillis() - startTime < 3_000L) {
}
});
t.start();
assertEquals(Thread.State.RUNNABLE, t.getState());
}
- TERMINATED结束
@Test
void testTerminatedState() throws InterruptedException {
Thread t = new Thread(() -> {
System.out.println("do something");
});
t.start();
t.join();
assertEquals(Thread.State.TERMINATED, t.getState());
}
- BLOCKED阻塞
获取object monitor时被阻塞
@Test
void testBlockedByGettingObjectMonitor() throws InterruptedException {
final Object mutex = new Object();
Runnable runnable = () -> {
synchronized (mutex) {
try {
Thread.sleep(5_000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread t1 = new Thread(runnable);
Thread t2 = new Thread(runnable);
t1.start();
t2.start();
Thread.sleep(2_000L);
assertEquals(Thread.State.BLOCKED, t2.getState());
}
- WAITING等待
- 调用object.wait()后
@Test
void testWaitingForSignal() throws InterruptedException {
final Object mutex = new Object();
Thread t1 = new Thread(() -> {
synchronized (mutex) {
try {
mutex.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
Thread.sleep(1_000L);
assertEquals(Thread.State.WAITING, t1.getState());
}
- 获取lock
@Test
void testWaitingForGetLock() throws InterruptedException {
Lock lock = new ReentrantLock();
Thread t1 = new Thread(() -> {
lock.lock();
try {
Thread.sleep(10_000L);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
});
Thread t2 = new Thread(() -> {
lock.lock();
try {
System.out.println("do something");
} finally {
lock.unlock();
}
});
t1.start();
t2.start();
Thread.sleep(2_000L);
assertEquals(Thread.State.WAITING, t2.getState());
}
- 等待Condition
@Test
void testWaitingForCondition() throws InterruptedException {
final Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
Thread t1 = new Thread(() -> {
lock.lock();
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
});
t1.start();
Thread.sleep(2_000L);
assertEquals(Thread.State.WAITING, t1.getState());
}