本文目錄一覽:
- 1、java線程的幾種狀態
- 2、java並發編程學習:如何等待多個線程執行完成
- 3、Java如何等待子線程執行結束
- 4、java 如何實現等待子線程結束
- 5、如何實現java主線程等待子線程執行完畢之後再執行
- 6、java如何等待方法內一個線程執行完畢
java線程的幾種狀態
總結了6種狀態,希望對你所有幫助:
1、NEW 狀態是指線程剛創建, 尚未啟動
2、RUNNABLE 狀態是線程正在正常運行中, 當然可能會有某種耗時計算/IO等待的操作/CPU時間片切換等, 這個狀態下發生的等待一般是其他系統資源, 而不是鎖, Sleep等
3、BLOCKED 這個狀態下, 是在多個線程有同步操作的場景, 比如正在等待另一個線程的synchronized 塊的執行釋放, 或者可重入的 synchronized塊里別人調用wait() 方法, 也就是這裡是線程在等待進入臨界區
4、WAITING 這個狀態下是指線程擁有了某個鎖之後, 調用了他的wait方法, 等待其他線程/鎖擁有者調用 notify / notifyAll 一遍該線程可以繼續下一步操作, 這裡要區分 BLOCKED 和 WATING 的區別, 一個是在臨界點外面等待進入, 一個是在臨界點裡面wait等待別人notify, 線程調用了join方法 join了另外的線程的時候, 也會進入WAITING狀態, 等待被他join的線程執行結束
5、TIMED_WAITING 這個狀態就是有限的(時間限制)的WAITING, 一般出現在調用wait(long), join(long)等情況下, 另外一個線程sleep後, 也會進入TIMED_WAITING狀態
6、TERMINATED 這個狀態下表示 該線程的run方法已經執行完畢了, 基本上就等於死亡了(當時如果線程被持久持有, 可能不會被回收)
java並發編程學習:如何等待多個線程執行完成
實現方式多種多樣,下面列兩種供參考:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws InterruptedException, ExecutionException {
System.out.println(“方式1”);
System.out.println(“================================================”);
// 方式1
// 創建一個線程池,並創建10個線程放入線程池執行
ExecutorService pool = Executors.newCachedThreadPool();
for (int i = 0; i 10; i++) {
pool.execute(new MyThread(“線程” + i));
}
// 線程池不再接收新任務
pool.shutdown();
// 線程池中的所有線程都執行完pool.isTerminated()才返回true
while (!pool.isTerminated()) {
Thread.sleep(100);
}
System.out.println(“所有線程執行完成”);
System.out.println(“\n\n方式2”);
System.out.println(“================================================”);
// 方式2
ExecutorService pool2 = Executors.newCachedThreadPool();
ListFuture futures = new ArrayList();
for (int i = 0; i 10; i++) {
// 使用實現Callable介面的方式創建線程,通過Future可以獲取線程中返回的結果
Future future = pool2.submit(new MyThread2(“線程” + i));
futures.add(future);
}
for (Future future : futures) {
// 該方法會阻塞主線程,直到線程執行完成
future.get();
}
System.out.println(“所有線程執行完成”);
}
}
class MyThread extends Thread {
private String name;
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + “執行完成”);
}
}
class MyThread2 implements Callable {
private String name;
public MyThread2(String name) {
this.name = name;
}
@Override
public Object call() throws Exception {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + “執行完成”);
return null;
}
}
Java如何等待子線程執行結束
先調用
shutdown
在調用
isTerminated
例:
/*
* 採用線程池開啟多個子線程,主線程等待所有的子線程執行完畢
*/
public static void moreThread() {
try {
int threadNum = 0;
for (int i = 0; i 10; i++) {
threadNum++;
final int currentThreadNum = threadNum;
exe.execute(new Runnable() {
@Override
public void run() {
try {
System.out.println(“子線程[” + currentThreadNum + “]開啟”);
Thread.sleep(1000*10);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
System.out.println(“子線程[” + currentThreadNum + “]結束”);
}
}
});
}
System.out.println(“已經開啟所有的子線程”);
exe.shutdown();
System.out.println(“shutdown():啟動一次順序關閉,執行以前提交的任務,但不接受新任務。”);
while(true){
if(exe.isTerminated()){
System.out.println(“所有的子線程都結束了!”);
break;
}
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
System.out.println(“主線程結束”);
}
}
java 如何實現等待子線程結束
有多種實現方式,下面列出兩種。
第一種:實現Callable類,使用有返回值的線程,只有線程執行完成後才會返回結果。
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
public class Main {
// 初始化一個容量為10的線程池
static final ExecutorService pool = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws ExecutionException, InterruptedException {
ListFutureString futures = new ArrayList();
for (int i = 0; i 3; i++) {
MyThread thread = new MyThread(“線程” + i);
futures.add(pool.submit(thread));
}
for (FutureString future : futures) {
String name = future.get();
System.out.println(name + “執行完成…”);
}
System.out.println(“所有線程執行完成!”);
}
}
class MyThread implements CallableString {
private String name;
public MyThread(String name) {
this.name = name;
}
@Override
public String call() throws Exception {
// TODO 執行業務
// 隨機延遲,模擬線程耗時
Thread.sleep(1000 + new Random().nextInt(2000));
return name;
}
}
第二種:使用CountDownLatch實現線程計數,代碼如下:
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main2 {
// 初始化一個容量為10的線程池
static final ExecutorService pool = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws InterruptedException {
int threadCount = 3;
// 初始化CountDownLatch,用於線程計數
CountDownLatch latch = new CountDownLatch(threadCount);
for (int i = 0; i threadCount; i++) {
MyThread thread = new MyThread(“線程” + i, latch);
pool.execute(thread);
}
// 阻塞當前線程,CountDownLatch計數減為0時表示所有線程都執行完畢,才會釋放主線程的阻塞
latch.await();
System.out.println(“所有線程執行完成!”);
}
}
class MyThread implements Runnable {
private String name;
private CountDownLatch latch;
public MyThread(String name, CountDownLatch latch) {
this.name = name;
this.latch = latch;
}
@Override
public void run() {
// TODO 執行業務
// 隨機延遲,模擬線程耗時
try {
Thread.sleep(1000 + new Random().nextInt(2000));
} catch (InterruptedException e) {
}
// 計數減一
latch.countDown();
System.out.println(name + “執行完畢…”);
}
}
如何實現java主線程等待子線程執行完畢之後再執行
在你的主線程中用一個join的方法,你要等待誰,就用誰調用,比如,你要等待線程a結束,就用a.join();這樣就可以了。記住哦,這條語句寫在哪個線程里,哪個線程就要等待調用這個方法的其他線程。就是說,你在主線程里寫了這條語句,那麼主線程就要等待線程a執行完後,主線程才會執行。
java如何等待方法內一個線程執行完畢
thread.Join把指定的線程加入到當前線程,可以將兩個交替執行的線程合併為順序執行的線程。比如在線程B中調用了線程A的Join()方法,直到線程A執行完畢後,才會繼續執行線程B。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/295215.html