天天看點

java 中的多線程 内部類實作 資料共享 和 Runnable實作資料共享

/*

java 中Runnable的好處    可以實作共享一個資料    

在一個類已經從其他類派生的時候 我們不能使用 直接從Thread類派生  那麼這時候我們可以通過實作Runnable

接口來實作 

  class Test

 {

    public  static void main(String []args)  throws Exception

     { 

       NewThread nt=new NewThread();

       new Thread(nt).start();

       new Thread(nt).start();     

       while(true)

     {

        System.out.println(Thread.currentThread().getName()+": is run");

     }

  }

class NewThread  implements Runnable

{

   int index=0;

    public    void run()

   {  while(true)

     //  System.out.println(Thread.currentThread().getName()+": is run");;

       System.out.println(Thread.currentThread().getName()+":"+index++);

      }

   }

}

*/

内部類也能實作多線程資料的共享  一般情況下我們是實作Runnable接口

       nt.getThread().start();

       nt.getThread().start();        

class NewThread 

    int index=0;

    private class InnerThread extends Thread   //設定為私有 隐藏 實作細節

   {

  } 

   Thread getThread()

    return new  InnerThread();