歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java並發編程--多線程之HelloWorld

Java並發編程--多線程之HelloWorld

日期:2017/3/1 9:29:04   编辑:Linux編程

上篇文章我們介紹了一些基本概念,進程、線程、並發(http://www.linuxidc.com/Linux/2015-05/118017.htm)。下面我們開始寫第一個多線程的程序。

兩種方式:一、實現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接口的方式可能更靈活一點。

Copyright © Linux教程網 All Rights Reserved