多线程例子: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
in mainThread-0 is blocked for 4734msThread-1 is blocked for 2307msThread-2 is blocked for 4562msjoin total time = 11609the result is 15
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次执行!