java多線程-合并

來源:互聯網
上載者:User

標籤:java多線程   線程   多線程   

java多線程-合并

線程合并的意義就是幾個並行的線程合并為一個單線程執行,應用於一個線程必須等待另個線程執行完畢後執行

例題:現有一個主線程,T1,T2怎麼讓T2在T1之後執行,主線程在T2之後執行

package cn.thread;public class ThreadJoin {    public static void main(String[] args) {        ThreadJoin join = new ThreadJoin();        Thread t1 = join.new MyThread1();        Thread t2 = new Thread(join.new MyRunnable());        t1.start();        t2.start();        for (int i = 0; i < 5; i++) {                       if (i==0)                try {                    // t1線程合并到主線程中,主線程停止執行過程,轉而執行t1線程,直到t1執行完畢後繼續。                    t1.join();                    // t2線程合并到主線程中,主線程停止執行過程,執行完t1線程,執行t2線程                    t2.join();                } catch (InterruptedException e) {                    e.printStackTrace();                }                System.out.println("主線程第" + i + "次執行!");        }    }    class MyThread1 extends Thread {        public void run() {            for (int i = 0; i < 5; i++) {                System.out.println("線程1第" + i + "次執行!");            }        }    }    class MyRunnable implements Runnable{    public void run() {          for(int i = 0;i < 5;i++){          System.out.println("線程2第"+i+"次執行! ");          }    }    }}




java多線程-合并

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.