首頁  >  文章  >  Java  >  java之Runnable介面建立執行緒詳解

java之Runnable介面建立執行緒詳解

怪我咯
怪我咯原創
2017-07-04 16:45:371051瀏覽

這篇文章主要介紹了java Runnable介面建立執行緒的相關資料,需要的朋友可以參考下

##java Runnable介面建立執行緒

建立一個線程,最簡單的方法是建立一個實作Runnable介面的類別。


為了實作Runnable,一個類別只需要執行一個方法呼叫run(),宣告如下:

public void run()

你可以重寫該方法,重要的是理解的run()可以呼叫其他方法,使用其他類,並聲明

變數,就像主執行緒一樣。

在建立一個實作Runnable介面的類別之後,你可以在類別中實例化一個執行緒

物件

Thread定義了幾個

建構方法,下面的這個是我們常用的:

Thread(Runnable threadOb,String threadName);

這裡,threadOb 是一個實作Runnable 介面的類別的實例,並且threadName指定新執行緒的名字。

新執行緒建立之後,你呼叫它的start()方法它才會運作。

void start();

實例

下面是一個建立執行緒並開始讓它執行的實例:

// 创建一个新的线程
class NewThread implements Runnable {
  Thread t;
  NewThread() {
   // 创建第二个新线程
   t = new Thread(this, "Demo Thread");
   System.out.println("Child thread: " + t);
   t.start(); // 开始线程
  }

  // 第二个线程入口
  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(); // 创建一个新线程
   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.");
  }
}

編譯以上程式執行結果如下:

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.

以上是java之Runnable介面建立執行緒詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn