亚洲一级免费看,特黄特色大片免费观看播放器,777毛片,久久久久国产一区二区三区四区,欧美三级一区二区,国产精品一区二区久久久久,人人澡人人草

java語言

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

時(shí)間:2025-05-18 05:20:51 java語言 我要投稿
  • 相關(guān)推薦

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

  導(dǎo)語:編寫多線程程序是為了實(shí)現(xiàn)多任務(wù)的并發(fā)執(zhí)行,從而能夠更好地與用戶交互。下面是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.


【java Runnable接口如何創(chuàng)建線程】相關(guān)文章:

java Runnable接口創(chuàng)建線程詳解10-30

如何創(chuàng)建并運(yùn)行Java線程10-01

如何使用java多線程08-23

java中如何停止線程08-14

淺談如何使用java多線程10-17

Java 如何進(jìn)行線程同步05-19

Java創(chuàng)建線程的三種方法07-26

java的多線程09-09

java多線程08-31