读书人

多线程例证:join

发布时间: 2012-09-22 21:54:54 作者: rapoo

多线程例子:join

package sure;import java.util.Random;public class MultThread {      public static void main(String[] args) {        System.out.println("in " + Thread.currentThread().getName());        long start = System.currentTimeMillis();        CounterThread[] ct = new CounterThread[3];        for (int i = 0; i < ct.length; i++) {            ct[i] = new CounterThread();            ct[i].start();//            try {//                ct[i].join();//            } catch (InterruptedException e) {//                e.printStackTrace();//            }        }        long end = System.currentTimeMillis();        System.out.println("join total time = " + (end - start));        int result = 0;        for (int j = 0; j < ct.length; j++) {            result += ct[j].getResult();        }        System.out.println("the result is " + result);    }}class CounterThread extends Thread {    public CounterThread() {    }    private int result;    public int getResult() {        return result;    }    public void run() {        try {            int time = (new Random().nextInt() >>> 1) % 5000;            Thread.sleep(time);            System.out.println(Thread.currentThread().getName()                    + " is blocked for " + time + "ms");        } catch (InterruptedException ex) {        }        result = 5;    }}

控制台结果是:
in mainjoin total time = 0the result is 0Thread-2 is blocked for 897msThread-0 is blocked for 1334msThread-1 is blocked for 4623ms

运行的直观感受是:
前三行一瞬间就出来了,就是说main线程没有收到任何阻塞,一下子就运行结束了。
其实这个时候三个子线程也在运行,不过sleep的阻塞时间有长短,因此就一个一个的执行完打印出了后面三行。

但是如果把//那几行放开,则结果变为:
in mainThread-0 is blocked for 4734msThread-1 is blocked for 2307msThread-2 is blocked for 4562msjoin total time = 11609the result is 15

运行的直观感受是:
第一行出来之后过了4734ms出现第二行,又过了2307ms出现第三行,又过了4562ms后面都出来了。
其实这就表明了join()的用处,就是:
比如在main线程中调用thread-0.join(),那么main线程就会阻塞,等到thread-0执行结束之后再继续运行main线程。
因此这个例子的代码实现了一个多线程进行汇总的功能,很有意思。


再来一个例子,也可以帮助加深理解:
public class Test {public static void main(String[] args) {Thread t1 = new MyThread1();t1.start();for (int i = 0; i < 20; i++) {System.out.println("主线程第" + i + "次执行!");if (i > 2)try {// t1线程合并到主线程中,主线程停止执行过程,转而执行t1线程,直到t1执行完毕后继续。t1.join();} catch (InterruptedException e) {e.printStackTrace();}}}}class MyThread1 extends Thread {public void run() {for (int i = 0; i < 10; i++) {System.out.println("线程1第" + i + "次执行!");}}}

控制台结果为:
线程1第0次执行!线程1第1次执行!线程1第2次执行!线程1第3次执行!线程1第4次执行!线程1第5次执行!主线程第0次执行!线程1第6次执行!主线程第1次执行!主线程第2次执行!主线程第3次执行!线程1第7次执行!线程1第8次执行!线程1第9次执行!主线程第4次执行!主线程第5次执行!主线程第6次执行!主线程第7次执行!主线程第8次执行!主线程第9次执行!主线程第10次执行!主线程第11次执行!主线程第12次执行!主线程第13次执行!主线程第14次执行!主线程第15次执行!主线程第16次执行!主线程第17次执行!主线程第18次执行!主线程第19次执行!

在主线程第3次执行!之后,会先执行完线程1,再返回主线程进行执行。

读书人网 >编程

热点推荐