爸爸和兒子的故事帶你理解java線程

來源:互聯網
上載者:User

標籤:name   pad   ring   out   generate   ted   含義   結果   stat   

  今天回想線程方面的知識,發現一個非常有意思的小程式。是用來說明多線程的以下貼出來分享下,對剛開始學習的人理解線程有非常大的協助

  爸爸和兒子的故事

<span style="font-family:KaiTi_GB2312;font-size:18px;">public class FatherThread extends Thread{        @Override      public void run() {          System.out.println("爸爸想抽煙。發現煙抽完了");          System.out.println("爸爸讓兒子去買包紅塔山");           Thread son = new SonThread();            son.start();              System.out.println("爸爸等兒子買煙回來");            try {                   //join含義:等待son線程運行完成,father線程才繼續運行                   son.join();              }          catch (InterruptedException e) {              System.out.println("爸爸出門去找兒子跑哪去了");              System.exit(1);          }              System.out.println("爸爸高興的接過煙開始抽,並把零錢給了兒子");                }            }  </span>
<span style="font-family:KaiTi_GB2312;font-size:18px;">public class SonThread extends Thread{        @Override      public void run() {          String tags ="\t\t\t\t\t";          System.out.println(tags+"兒子去買煙了");          System.out.println(tags+"兒子去買煙要10分鐘");          try {              for(int i =0; i<10;){                  Thread.sleep(1000);                  System.out.println(tags+"兒子出去第"+ ++i +"分鐘");              }          } catch (InterruptedException e) {              e.printStackTrace();                        }          System.out.println(tags+"兒子去買煙回來了");      }        }  </span>
<span style="font-family:KaiTi_GB2312;font-size:18px;">public class Main {      public static void main(String[] args){          System.out.println("爸爸和兒子的故事");          Thread faThread =new FatherThread();          faThread.start();          try {              Thread.sleep(5000);          } catch (InterruptedException e) {              // TODO Auto-generated catch block              e.printStackTrace();          }      }  }  </span>


執行結果
爸爸和兒子的故事
爸爸想抽煙,發現煙抽完了
爸爸讓兒子去買包紅塔山
爸爸等兒子買煙回來
兒子去買煙了
兒子去買煙要10分鐘
兒子出去第1分鐘
兒子出去第2分鐘
兒子出去第3分鐘
兒子出去第4分鐘
兒子出去第5分鐘
兒子出去第6分鐘
兒子出去第7分鐘
兒子出去第8分鐘
兒子出去第9分鐘
兒子出去第10分鐘
兒子去買煙回來了
爸爸高興的接過煙開始抽,並把零錢給了兒子

  程式進入主函數,首先father線程開始運行。爸爸讓兒子去買煙,然後等待兒子買煙回來。這時son線程啟動10分鐘後兒子回來fathrer線程繼續運行。



爸爸和兒子的故事帶你理解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.