联合线程实际上就是把多线程又联合成了一个线程,但这里还是要比单线程灵活很多,比如说,我可以让一个线程到运行到某一个条件再联合其他线程。当前线程与其他线程联合在一起,又一种让出cpu,而且直到别个线程运行完,当然,这里join()还可以传入时间以控制联合的时间
联合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秒,然后在分别运行。

1087

被折叠的 条评论
为什么被折叠?



