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



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

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