Java線程的實現有兩種方式:

1 通過繼承Thread類來實現。

每個線程都是通過某個特定Thread對象所對應的方法run()l來完成其操作的,方法run()成為線程體。

如果想要啟動多線程,則肯定調用start()方法,start方法可以調用被子類覆寫過的run方法

不過這種這種實現方式會受到單繼承的局限

 

示例代碼:

package com.dr.demo01;

//一個類只要繼承了Thread類,則此類就是多線程類

class MyThread extends Thread{

       private String name;

       public MyThread(String name){

              this.name=name;

       }

       //如果要使用多線程,則必須有一個方法的主體

       public void run(){

              //打印輸出

              for(int i=0;i<15;i++){

                     System.out.println(this.name+"--->在運行、、、");

              }

       }

}

public class ThreadDemo01{

       public static void main(String args[]){

              MyThread mt1=new MyThread("線程A");

              MyThread mt2=new MyThread("線程B");

              MyThread mt3=new MyThread("線程C");

              mt1.run();

              mt2.run();

              mt3.run();

       }

}

 

2 通過實現Runnable接口來實現。

該實現方式有以下好處:

     適合多個相干同程序代碼的線程去處理同一資源的情況。

     可以避免由于Java單繼承特性帶來的局限。

     有利于程序的健壯性,代碼能夠被多個線程共享。

 

示例代碼:

package com.dr.Demo05;

class MyThread implements Runnable{

    public void run(){

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

           try{

              Thread.sleep(1000);

           }catch(Exception e){}

           System.out.println(Thread.currentThread().getName()+"--運行中--");

       }

    }

}

public class Demo05 {

 

   

    public static void main(String[] args) {

       MyThread mt=new MyThread();

       Thread t1=new Thread(mt,"線程A");

       Thread t2=new Thread(mt,"線程B");

       Thread t3=new Thread(mt,"線程C");

       t1.start();

       t2.start();

       t3.start();

    }

 

}