@Test
public void threadTest() throws Exception {
int count = 10;
List<Thread> threads = new ArrayList<>();
for(int i = 0; i < count; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("執行子線程");
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
threads.add(thread);
}
for(int i = 0; i < count; i++) {
/** 等待線程執行完成(阻塞)
* 阻塞狀態(blocking):調用sleep方法,調用別的線程的join方法,執行I/O操做線程進入阻塞狀態;
* 解除阻塞:睡眠狀態超時,調用join的線程執行完畢後,I/O操做完畢,調用阻塞線程的interrupt(中斷)方法,會拋出
* */
threads.get(i).join();
}
System.out.println("執行主線程");
}
ide
執行子線程Thread-13----:1534388413578
執行子線程Thread-14----:1534388413578
執行子線程Thread-15----:1534388413578
執行子線程Thread-16----:1534388413578
執行子線程Thread-17----:1534388413578
執行子線程Thread-18----:1534388413579
執行子線程Thread-19----:1534388413579
執行子線程Thread-20----:1534388413579
執行子線程Thread-21----:1534388413579
執行子線程Thread-22----:1534388413579
執行主線程main----:1534388423584
spa