JAvaスレッドの作成の2つの方法と違い

1466 ワード

ここでは、スレッドを作成する2つの方法について説明します.サンプルコードは以下のとおりです.コピーして貼り付けます.
Threadクラス方式の継承とRunnableインタフェース方式の実装
違い:開発の過程で多くのクラスが継承方式を用いるため,継承方式を採用すると各クラス間の関係が複雑になる
プログラムの可読性が悪くなるため,開発ではインタフェースを実現する方式が一般的であり,インタフェースを実現する方式ではリソースを共有し,リソースを共有することもできる.
例は後述する.
/*
 *           :    
 * 1.     ,  Thread 
 * 2.     run  ,  run    public  ,       
 * 3.           
 * 4.       start  
 */
class xiancheng extends Thread//   
{
    public void run() //   
    {
        for(int x=0;x<60;x++) 
        {
            System.out.println("1");
        }
    }
}

public class Test1 {

    public static void main(String[] args) 
    {
        xiancheng t=new xiancheng();//   
        t.start();//   
        for(int x=0;x<500;x++) 
        {
            System.out.println("2");
        }
    }

}
/*
 *           :    
 * 1.        Runnable  
 * 2.  Runnable  run  
 * 3.  Runnable       
 * 4.              Thread       
 * 5.  start      
 */
class xiancheng1 implements Runnable//   
{
    public void run() //   
    {
        for(int x=0;x<60;x++) 
        {
            System.out.println("1");
        }
    }
}
public class Test2 {

    public static void main(String[] args) 
    {
        xiancheng1 t=new xiancheng1();//   
        Thread t1=new Thread(t);//   
        t1.start();//   
        for(int x=0;x<500;x++) //   
        {
            System.out.println("2");
        }
    }

}