日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

java 主线程等待_Java实现主线程等待子线程

發(fā)布時(shí)間:2024/9/27 java 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java 主线程等待_Java实现主线程等待子线程 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

本文介紹兩種主線程等待子線程的實(shí)現(xiàn)方式,以5個(gè)子線程來說明:

1、使用Thread的join()方法,join()方法會(huì)阻塞主線程繼續(xù)向下執(zhí)行。

2、使用Java.util.concurrent中的CountDownLatch,是一個(gè)倒數(shù)計(jì)數(shù)器。初始化時(shí)先設(shè)置一個(gè)倒數(shù)計(jì)數(shù)初始值,每調(diào)用一次countDown()方法,倒數(shù)值減一,他的await()方法會(huì)阻塞當(dāng)前進(jìn)程,直到倒數(shù)至0。

join方式代碼如下:

package com.test.thread;

import java.util.ArrayList;

import java.util.List;

public class MyThread extends Thread

{

public MyThread(String name)

{

this.setName(name);

}

@Override

public void run()

{

System.out.println(this.getName() + " staring...");

System.out.println(this.getName() + " end...");

}

/**

* @param args

*/

public static void main(String[] args)

{

System.out.println("main thread starting...");

List list = new ArrayList();

for (int i = 1; i <= 5; i++)

{

MyThread my = new MyThread("Thrad " + i);

my.start();

list.add(my);

}

try

{

for (MyThread my : list)

{

my.join();

}

}

catch (InterruptedException e)

{

e.printStackTrace();

}

System.out.println("main thread end...");

}

}

運(yùn)行結(jié)果如下:

main thread starting...

Thrad 2 staring...

Thrad 2 end...

Thrad 4 staring...

Thrad 4 end...

Thrad 1 staring...

Thrad 1 end...

Thrad 3 staring...

Thrad 3 end...

Thrad 5 staring...

Thrad 5 end...

main thread end...

CountDownLatch方式代碼如下:

package com.test.thread;

import java.util.concurrent.CountDownLatch;

public class MyThread2 extends Thread

{

private CountDownLatch count;

public MyThread2(CountDownLatch count, String name)

{

this.count = count;

this.setName(name);

}

@Override

public void run()

{

System.out.println(this.getName() + " staring...");

System.out.println(this.getName() + " end...");

this.count.countDown();

}

/**

* @param args

*/

public static void main(String[] args)

{

System.out.println("main thread starting...");

CountDownLatch count = new CountDownLatch(5);

for (int i = 1; i <= 5; i++)

{

MyThread2 my = new MyThread2(count, "Thread " + i);

my.start();

}

try

{

count.await();

}

catch (InterruptedException e)

{

e.printStackTrace();

}

System.out.println("main thread end...");

}

}

運(yùn)行結(jié)果如下:

main thread starting...

Thread 2 staring...

Thread 2 end...

Thread 4 staring...

Thread 4 end...

Thread 1 staring...

Thread 1 end...

Thread 3 staring...

Thread 3 end...

Thread 5 staring...

Thread 5 end...

main thread end..

轉(zhuǎn)自http://blog.csdn.net/nms312/article/details/30115055

總結(jié)

以上是生活随笔為你收集整理的java 主线程等待_Java实现主线程等待子线程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。