多线程并行执行与顺序执行(一)

package test; import java.util.Vector; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 通过 join()方法并行执行线程。 * @author Smile */ public class ThreadJoinTest { public static void main(String[] args) throws InterruptedException { test1(); test2(); test3(); } public static void test1() throws InterruptedException { mThread t1 = new mThread("t1--------"); mThread t2 = new mThread("t2"); t1.start(); /**t1.join(); join()不传递参数,表示t1线程执行完成之后执行t2线程。 * *t1.join(10); join()传递参数,join(10)表示主线程会等待t1线程10毫秒,10毫秒过去后, *主线程和t1线程之间执行顺序由串行执行变为普通的并行执行。 * *(个人认为这种方式在非main方法中使用,存在线程进行中,方法结束导致线程终止的情况。) */ t1.join(10); t2.start(); System.out.println("执行完毕!----------test1-----------"); } public static void test2() throws InterruptedException { Vector vectors=new Vector(); mThread t1 = new mThread("t1-----"); mThread t2 = new mThread("t2"); t1.start(); t2.start(); vectors.add(t1); vectors.add(t2); /** * 经过for循环遍历,两个线程会并行执行,并在两个线程都执行完毕后,执行主线程。 */ for (Thread thread : vectors) { thread.join(); } System.out.println("执行完毕!-----------test2------------"); } /** * 通过 线程池 */ public static void test3() throws InterruptedException { final Thread t1 = new Thread(new Runnable() { public void run() { for (int i = 1; i <= 100; i++) { System.out.println("---t1---"); } } }); final Thread t2 = new Thread(new Runnable() { public void run() { for (int i = 1; i <= 100; i++) { System.out.println("---t2---"); } } }); final Thread t3 = new Thread(new Runnable() { public void run() { for (int i = 1; i <= 100; i++) { System.out.println("---t3---"); } } }); //此方法使用 单个任务的线程池来实现。保证线程的依次执行 ExecutorService executor = Executors.newSingleThreadExecutor(); executor.submit(t1); executor.submit(t2); executor.submit(t3); executor.shutdown(); // 结束进程 } } class mThread extends Thread{ public mThread(String name){ super(name); } @Override public void run(){ for(int i=1; i<=1000; i++){ System.out.println(this.getName() + "--------" + i); } } }

【多线程并行执行与顺序执行(一)】

    推荐阅读