JAVA中建立多線程的典型例子

來源:互聯網
上載者:User

JAVA中建立多線程,無非兩種方式,一是繼承自thread類,另一種是實現runnable介面,下面兩個例子很典型,可以複習下
1、繼承自thread類
  

public class j02140301 extends Thread  // 步驟 1
{
  public void run()   // 步驟 2 ,覆蓋繼承自 Thread 的 run()
  {
    while(true)
    { 
      System.out.print("X ");
      //....
      try
      {
        Thread.sleep(1000);  // 此線程要休眠 1 秒       
      }
      catch(InterruptedException e){/*...*/}
    }  
  }
 
  public static void main(String abc[])
  {
    Thread ThreadObj1 = new myDog();   
    ThreadObj1.start();     //  自動調用  run()
   
    Thread ThreadObj2 = new j02140301();   
    ThreadObj2.start();     //   自動調用  run()
   
   
    for(int x=1;x<=5;x++)// main thread 執行此 for 敘述句
    { 
     System.out.print("A ");
    }
    System.out.println();   
  } //到此 main thread 就停了
}

//=======================================================
//另一個繼承 Thread 的類
class myDog extends Thread  // 步驟 1
{
  public void run()   // 步驟 2
  {
    System.out.print("dog ");  
  }
}

2、public class j02140302 implements Runnable  // 步驟 1
{
  public void run()   // 步驟 2
  {
    while(true)
    { 
      System.out.println("歡迎~~ ");
      //....
      try
      {
        Thread.sleep(1000);  // 休眠 1000 毫秒
      }
      catch(InterruptedException e){  }
    }  
  } 
 
  public static void main(String abc[])
  {   
    Thread ThreadObj1 = new Thread( new welcome() );   // 步驟 3 ,利用 Runnable 對象建構 Thread 對象
    ThreadObj1.start();     // 步驟 4   自動調用 welcome 實現的 run()
   
    Thread ThreadObj2 = new Thread( new j02140302() );   // 步驟 3 ,利用 Runnable 對象建構 Thread 對象
    ThreadObj2.start();     // 步驟 4   自動調用 j02140302 實現的 run()     
  }
}

class myFriend
{
  public void sayHello()
  {
    System.out.println("朋友!好久不見!");
  }
}

class welcome extends myFriend implements Runnable   // 步驟 1    
{             //擁有 myFriend 的執行個體,也有 Runnable 的執行個體                          
  public void run()   // 步驟 2
  { 
    while(true)
    {
      sayHello();
      try
      {
        Thread.sleep(3000);   // 休眠 3000 毫秒
      }
      catch(InterruptedException e){  }
    }
  } 
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.