天天看點

Java實作多線程的兩種方式

1:繼承Thread類,子類就是線程類,子類中内容就是線程任務;直接建立子類對象,并調用start()方法即可啟動線程。

public class MyThread extends Thread{ 

    @Override

    public void run(){ 

         System.out.println("目前線程的名字="+Thread.currentThread().getName());

    } 

}

public class Run {

    public static void main(String[] args) {

        MyThread myThread=new MyThread();

        myThread.start();

        System.out.println("運作結束!");

    }

2:實作Runnable接口,但是實作類不是線程類,而是線程任務類,實作類中的内容是線程任務;在建立Thread對象時,把實作類的對象傳進去,最終調用Thread對象的start()方法即可開啟新線程。

public class myRunnable implements Runnable {

    public void  run(){

        System.out.println("運作中!");

        Runnable runnable=new myRunnable();

        Thread thread=new Thread(runnable);

        thread.start();

兩者的差別:

1:使用Thread的子類來建立線程的話,任務都在Thread的子類中定義。