一个线程在占用CPU资源期间,可以让其他线程调用join()和本线程联合。如果,一个线程A联合了线程B,那么线程A将立刻中断执行,一直等到它联合的线程B执行完毕,线程A再重新排队等待CPU资源,以便恢复执行。
1. 如果线程A在占有CPU期间,一旦联合了线程B,那么线程A将立刻中断执行;直到它联合的线程B执行完毕,然后线程A再重新排队等待切换CPU资源,以便恢复执行。
2. 如果线程A联合的线程B已经结束,那么B.join()将不会产生任何效果。
3. 线程A重新获取到CPU资源后,继续执行没有执行完的内容。
package com.what21.thread02;
public class ThreadTest01 {
/**
* @param args
*/
public static void main(String[] args) {
Thread t = new ThreadA();
t.setName("AAAAAA");
t.start();
}
}
class ThreadA extends Thread {
public void run() {
Thread t = new ThreadB();
t.setName("BBBBBB");
t.start();
for (int i = 1; i < 5; i++) {
System.out.println("Thread: " + this.getName() + " join before "
+ i);
try {
Thread.sleep(1 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
System.out.println("Thread: " + this.getName() + " join ");
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 1; i < 11; i++) {
System.out
.println("Thread: " + this.getName() + " join after " + i);
try {
Thread.sleep(1 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class ThreadB extends Thread {
public void run() {
for (int i = 1; i < 11; i++) {
System.out
.println("Thread: " + this.getName() + " is running " + i);
try {
Thread.sleep(1 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}