1,联合线程实际上就是把多线程又联合成了一个线程,但这里还是要比单线程灵活很多,比如说,我可以让一个线程到运行到某一个条件再联合其他线程。当前线程与其他线程联合在一起,又一种让出cpu,而且直到别个线程运行完,当然,这里join()还可以传入时间以控制联合的时间。
a,直接联合:
public class ThreadDemo {
public static void main(String[] args) {
Thread t = new TestThread();
// t.setDaemon(true);
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
while(true) {
System.out.println("main(): "+Thread.currentThread().getName() + " is running");
}
}
}
class TestThread extends Thread {
public void run() {
while(true) {
System.out.println("TestThread: "+Thread.currentThread().getName() + " is running");
}
}
}
这种直接联合,2个线程就完全成了一个线程了。
b,条件联合:
public class ThreadDemo {
public static void main(String[] args) {
Thread t = new TestThread();
// t.setDaemon(true);
t.start();
int i=0;
while(true) {
System.out.println("main(): "+Thread.currentThread().getName() + " is running");
if(i++ ==10000) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class TestThread extends Thread {
public void run() {
while(true) {
System.out.println("TestThread: "+Thread.currentThread().getName() + " is running");
}
}
}
这里当main线程中工作10000下后,把线程TestThread 联合进来,实际上就是main线程运行10000下后,一直等到TestThread 完成后,再运行。
这里说个题外话,在试验这种死循环的java程序时最好在命令行窗口中试验(cmd中),因为那里ctrl+c中断非常地方便,现在我都是有eclipse,在eclipse中运行时常运行死了,因为图形界面的东东,本来就需要线程去刷新图形界面去,如果程序引入了一个死循环进去,eclipse就没有能力捕捉到你所按得Terminate键了。同时,在eclipse中写的java程序,找到生成的class文件,直接运行也是一个不错的选择,但要注意不要忘了下上完整的包名。如我一开始就遇到了这个问题:ThreadDemo放在了fsf的包下面,然后到cmd切换到fsf目录下运行java ThreadDemo结果总是报错“Exception in thread "main" java.lang.NoClassDefFoundError: ThreadDemo (wrong name: fsf/ThreadDemo)”。一开始以为是classpath没有设好,结果把fsf的完整路径设到classpath中去,还是报同样错误。后来才发现,要到fsf上一层目录运行“java fsf/ThreadDemo”。
c,联合10秒和分开;
public class ThreadDemo {
public static void main(String[] args) {
Thread t = new TestThread();
// t.setDaemon(true);
t.start();
int i=0;
while(true) {
System.out.println("main(): "+Thread.currentThread().getName() + " is running");
if(i++ ==10000) {
try {
t.join(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class TestThread extends Thread {
public void run() {
while(true) {
System.out.println("TestThread: "+Thread.currentThread().getName() + " is running");
}
}
}
这里当main线程运行10000下后,与TestThread 联合10秒,其实就是让TestThread 运行10秒,然后在分别运行。