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.