最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java Runnable接口創(chuàng)建線程

 更新時(shí)間:2017年07月03日 16:45:59   投稿:lqh  
這篇文章主要介紹了java Runnable接口創(chuàng)建線程的相關(guān)資料,需要的朋友可以參考下

java Runnable接口創(chuàng)建線程

創(chuàng)建一個(gè)線程,最簡(jiǎn)單的方法是創(chuàng)建一個(gè)實(shí)現(xiàn)Runnable接口的類。

為了實(shí)現(xiàn)Runnable,一個(gè)類只需要執(zhí)行一個(gè)方法調(diào)用run(),聲明如下:

public void run()

你可以重寫該方法,重要的是理解的run()可以調(diào)用其他方法,使用其他類,并聲明變量,就像主線程一樣。

在創(chuàng)建一個(gè)實(shí)現(xiàn)Runnable接口的類之后,你可以在類中實(shí)例化一個(gè)線程對(duì)象。

Thread定義了幾個(gè)構(gòu)造方法,下面的這個(gè)是我們經(jīng)常使用的:

Thread(Runnable threadOb,String threadName);

這里,threadOb 是一個(gè)實(shí)現(xiàn)Runnable 接口的類的實(shí)例,并且 threadName指定新線程的名字。
新線程創(chuàng)建之后,你調(diào)用它的start()方法它才會(huì)運(yùn)行。

void start();

實(shí)例

下面是一個(gè)創(chuàng)建線程并開始讓它執(zhí)行的實(shí)例:

// 創(chuàng)建一個(gè)新的線程
class NewThread implements Runnable {
  Thread t;
  NewThread() {
   // 創(chuàng)建第二個(gè)新線程
   t = new Thread(this, "Demo Thread");
   System.out.println("Child thread: " + t);
   t.start(); // 開始線程
  }

  // 第二個(gè)線程入口
  public void run() {
   try {
     for(int i = 5; i > 0; i--) {
      System.out.println("Child Thread: " + i);
      // 暫停線程
      Thread.sleep(50);
     }
   } catch (InterruptedException e) {
     System.out.println("Child interrupted.");
   }
   System.out.println("Exiting child thread.");
  }
}

public class ThreadDemo {
  public static void main(String args[]) {
   new NewThread(); // 創(chuàng)建一個(gè)新線程
   try {
     for(int i = 5; i > 0; i--) {
      System.out.println("Main Thread: " + i);
      Thread.sleep(100);
     }
   } catch (InterruptedException e) {
     System.out.println("Main thread interrupted.");
   }
   System.out.println("Main thread exiting.");
  }
}

編譯以上程序運(yùn)行結(jié)果如下:

Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

最新評(píng)論

康保县| 筠连县| 巢湖市| 宜兰市| 大田县| 桐庐县| 渑池县| 林州市| 五河县| 永川市| 万载县| 娄烦县| 图木舒克市| 涿州市| 石泉县| 山丹县| 红安县| 土默特左旗| 金秀| 时尚| 罗源县| 西吉县| 洞头县| 怀化市| 安仁县| 友谊县| 冀州市| 宁化县| 炉霍县| 台南市| 泊头市| 蒙阴县| 澳门| 祁东县| 莱阳市| 普宁市| 论坛| 万全县| 舒兰市| 乌兰察布市| 老河口市|