Thread 实例的 join() 方法可用于将一个线程的执行开始“连接”到另一个线程的执行结束,以便一个线程在另一个线程结束之前不会开始运行。如果在 Thread 实例上调用 join(),则当前正在运行的线程将阻塞,直到 Thread 实例完成执行
但是如果 ia 有多个线程并且当我在循环内调用 join 时。所有线程并行运行。但是根据连接概念,首先连接的线程应该完成,然后只有主线程应该允许连接其他线程。
public class MultiThreading implements Runnable {
private int name;
public MultiThreading(int number) {
name =number;
}
@Override
public void run() {
for (int i = 0; i <= 10; i++ ) {
System.out.println("Thread number :" + name +" Printed value "+i);
try {
Thread.sleep(100);
} catch (final InterruptedException e) {
return;
}
}
}
public static void main(String[] args) throws InterruptedException {
final Thread[] workers = new Thread[3];
for (int i = 0; i < nthreads; ++i) {
workers[i] = new Thread(new MultiThreading(i));
}
for (final Thread t : workers) {
t.start();
}
for (final Thread t : workers) {
t.join();
System.out.println("Thread joind to main thread : " + t.getName());
}
System.out.println("Main thread ends");
}
}
在上面的代码中,如果第一个线程被加入,那么主线程应该被阻塞并且不应该让其他线程加入(直到被加入的线程完成run方法的执行)。但是所有线程都是并行连接的。输出就像 -
Thread number :0 Printed value 0
Thread number :1 Printed value 0
Thread number :2 Printed value 0
Thread number :0 Printed value 1
Thread number :1 Printed value 1
Thread number :2 Printed value 1
Thread number :0 Printed value 2
Thread number :1 Printed value 2
Thread number :2 Printed value 2
Thread number :0 Printed value 3
Thread number :1 Printed value 3
Thread number :2 Printed value 3
Thread number :0 Printed value 4
Thread number :1 Printed value 4
Thread number :2 Printed value 4
Thread number :1 Printed value 5
犯罪嫌疑人X
相关分类