| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 460 人关注过本帖
标题:java线程中join()方法使用
只看楼主 加入收藏
shitainong
Rank: 1
等 级:新手上路
帖 子:70
专家分:0
注 册:2012-7-6
结帖率:0
收藏
 问题点数:0 回复次数:2 
java线程中join()方法使用
Java代码

1.public class JoinThread extends Thread {

2.

3. public static int n = 0;

4.

5. static synchronized void inc() {

6. n++;

7. }

8.

9. public void run() {

10. for (int i = 0; i < 10; i++) {

11. try {

12. inc();

13. System.out.println(n);

14. sleep(3); // 为了使运行结果更随机,延迟3毫秒

15. } catch (Exception e) {

16. }

17.

18. }

19. }

20.

21. public static void main(String[] args) throws Exception {

22. Thread threads[] = new Thread[100];

23. for (int i = 0; i < threads.length; i++) // 建立100个线程

24. {

25. threads[i] = new JoinThread();

26. }

27. for (int i = 0; i < threads.length; i++) // 运行刚才建立的100个线程

28. {

29. threads[i].start();

30. }

31.// if (args.length > 0) {

32. for (int i = 0; i < threads.length; i++) // 100个线程都执行完后继续

33. {

34. threads[i].join(); //必须这个线程执行完,当前线程才能继续执行

35. }

36.// }

37. System.out.println(“n=” + JoinThread.n);

38. }

39.}

public class JoinThread extends Thread {

public static int n = 0;

static synchronized void inc() {

n++;

}

public void run() {

for (int i = 0; i < 10; i++) {

try {

inc();

System.out.println(n);

sleep(3); // 为了使运行结果更随机,延迟3毫秒

} catch (Exception e) {

}

}

}

public static void main(String[] args) throws Exception {

Thread threads[] = new Thread[100];

for (int i = 0; i < threads.length; i++) // 建立100个线程

{

threads[i] = new JoinThread();

}

for (int i = 0; i < threads.length; i++) // 运行刚才建立的100个线程

{

threads[i].start();

}

// if (args.length > 0) {

for (int i = 0; i < threads.length; i++) // 100个线程都执行完后继续

{

threads[i].join(); //必须这个线程执行完,当前线程才能继续执行

}

// }

System.out.println(“n=” + JoinThread.n);

}

}

使当前线程必须等待调用join的线程执行完,才能继续执行.www.

搜索更多相关主题的帖子: void public sleep Java 
2012-12-10 14:36
w527705090
Rank: 10Rank: 10Rank: 10
等 级:贵宾
威 望:11
帖 子:441
专家分:1882
注 册:2011-6-28
收藏
得分:0 
看到你最后的那个网站。。。是某某培训机构的吧。。。还是去问问你的老师吧。。。

有心者,千方百计;无心者,千难万难。
2012-12-13 18:58
chenfumig
Rank: 2
等 级:论坛游民
威 望:1
帖 子:12
专家分:12
注 册:2012-12-9
收藏
得分:0 
那机构的周羽老师昨天才到我们学校开讲座!!
2012-12-15 11:30
快速回复:java线程中join()方法使用
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.011387 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved