天天看點

java中建立兩種線程的方式_java中建立線程的兩種方式有什麼差別?

*** 一.建立線程

1.繼承Thread類

定義類繼承Thread, 重寫run()方法, 将線程中要執行的代碼寫在run()方法中

建立該類對象, 調用start()方法就可以開啟一條新線程, 新線程中自動指定run()方法

public class ThreadDemo1 {

public static void main(String[] args) {

// 3.建立線程對象

MyThread mt = new MyThread();

// 4.啟動一條新線程, 新線程上自動執行run()方法

mt.start();

// 5.主線程循環列印

for (int i = 0; i < 100; i++)

System.out.println("A " + i);

}

}

// 1.定義類繼承Thread

class MyThread extends Thread {

// 2.重寫run方法

public void run() {

for (int i = 0; i < 100; i++)

System.out.println("B " + i);

}

}

2.實作Runnable接口

定義類實作Runnable接口, 重寫run()方法, 将線程中要執行的代碼寫在run()方法中

建立該類對象, 建立Thread類對象, 将Runnable對象傳入Thread的構造函數中

調用Thread對象的start()方法就可以開啟一條新線程, 新線程中執行Runnable的run()方法

public class ThreadDemo2 {

public static void main(String[] args) {

// 3.建立Runnable對象

MyRunnable mr = new MyRunnable();

// 4.建立Thread對象, 在構造函數中傳入Runnable對象

Thread t = new Thread(mr);

// 5.調用start()開啟新線程, 新線程自動執行Runnable的run()方法

t.start();

// 6.主線程循環列印

for (int i = 0; i < 100; i++)

System.out.println("A " + i);

}

}

// 1.定義類, 實作Runnable接口

class MyRunnable implements Runnable {

// 2.實作run()方法

public void run(){

for (int i = 0; i < 100; i++)

System.out.println("B " + i);

}

}