程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java多線程初學者指南(3):使用Runnable接口創建線程

Java多線程初學者指南(3):使用Runnable接口創建線程

編輯:關於JAVA

實現Runnable接口的類必須使用Thread類的實例才能創建線程。通過Runnable接口創建線程分為兩步:

1.將實現Runnable接口的類實例化。

2.建立一個Thread對象,並將第一步實例化後的對象作為參數傳入Thread類的構造方法。

最後通過Thread類的start方法建立線程。

下面的代碼演示了如何使用Runnable接口來創建線程:

package mythread;

public class MyRunnable implements Runnable
{
 public void run()
 {
  System.out.println(Thread.currentThread().getName());
 }
 public static void main(String[] args)
 {
  MyRunnable t1 = new MyRunnable();
  MyRunnable t2 = new MyRunnable();
  Thread thread1 = new Thread(t1, "MyThread1");
  Thread thread2 = new Thread(t2);
  thread2.setName("MyThread2");
  thread1.start();
  thread2.start();
 }
}

上面代碼的運行結果如下:

MyThread1
MyThread2

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved