Java併發程式設計--多執行緒之HelloWorld
阿新 • • 發佈:2019-01-29
上篇部落格我們介紹了一些基本概念,程序、執行緒、併發。下面我們開始寫第一個多執行緒的程式。
兩種方式:一、實現Runnable介面;二、基礎Thread類。
一、實現Runnable介面
package com.tgb.klx.thread; public class hello1 implements Runnable { public hello1() { } public hello1(String name) { this.name = name; } public void run() { for (int i = 0; i < 5; i++) { System.out.println(name + "執行 " + i); } } public static void main(String[] args) { hello1 h1 = new hello1("執行緒A"); Thread demo1 = new Thread(h1); hello1 h2 = new hello1("執行緒B"); Thread demo2 = new Thread(h2); demo1.start(); demo2.start(); } private String name; }
執行結果:
二、基於Thread類
package com.tgb.klx.thread; public class hello2 extends Thread { public hello2() { } public hello2(String name) { this.name = name; } public void run() { for (int i = 0; i < 5; i++) { System.out.println(name + "執行 " + i); } } public static void main(String[] args) { hello2 h1 = new hello2("A"); hello2 h2 = new hello2("B"); h1.start(); h2.start(); } private String name; }
執行結果:
實現Runnable介面的方式,需要建立一個Thread類,將實現runnable的類的例項作為引數傳進去,啟動一個執行緒,如果直接呼叫runnable的run方法跟呼叫普通類的方法沒有區別,不會建立新的執行緒。
Thread類實現了Runnable介面,Thread類也有run方法,呼叫Thread的run方法同樣也不會新建執行緒,和呼叫普通方法沒有區別,所以大家在使用多執行緒時一定要注意。
總結:
以上兩種方式都可以實現,具體選擇哪種方式根據情況決定。java裡面不支援多繼承,所以實現runnable介面的方式可能更靈活一點。