3種啟動線程的方式


線程和進程的關系:  一個進程有N個線程

 

1、實現線程的三種方式:

(1)繼承thread 類

    [1]創建一個繼承thread類的類

    

package Thread01;

public class MyThread extends Thread {
    private int i;

    @Override
    public void run() {
       for (; i < 10; i++) {
         System.out.println(getName()+"\t"+i);
    }
    }
}

 

    [2]創建測試類

package Thread01;

public class MyTest {
    public static void main(String[] args) {
        for (int i = 0; i <10; i++) {
             System.out.println(Thread.currentThread().getName()+"\t"+i+"======");
             if(i==5){
                 
                 MyThread mt2 =new MyThread();
                 MyThread mt =new MyThread();
                 mt2.start();
                 mt.start();
             }
        }
    }
    
    public static long getMemory() {
           return Runtime.getRuntime().freeMemory();
        }
}

 

(2)實現runnable 接口

 

  【1】 實現runnable 接口的類並不是一個線程類,而是線程類的一個target ,可以為線程類構造方法提供參數來實現線程的開啟

     

package Thread02;

public class SecondThread implements Runnable{
    private int i;
    public void run() {
        for (; i < 20; i++) {
            System.out.println(Thread.currentThread().getName()+" "+i);
            if(i==20)
            {
                System.out.println(Thread.currentThread().getName()+"執行完畢");
            }
        }
    }
}

 

  【2】測試類

package Thread02;

public class MyTest {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName()+" "+i);
            if(i==5)
            {
                SecondThread s1=new SecondThread();
                Thread t1=new Thread(s1,"線程1");
                Thread t2=new Thread(s1,"線程2");
                t1.start();
                t2.start();
               
            }
        }
    }
}

 

(3)實現callable 接口

  【1】創建callable 實現類

  

package Thread03;

import java.util.concurrent.Callable;

public class Target implements Callable<Integer> {
    int i=0;
    public Integer call() throws Exception {
        for (; i < 20; i++) {
            System.out.println(Thread.currentThread().getName()+""+i);
        }
        return i;
    }

}

 

  【2】測試類

  

package Thread03;

import java.util.concurrent.FutureTask;

public class ThirdThread {
     public static void main(String[] args) {
            Target t1=new Target();
            FutureTask<Integer> ft=new FutureTask<Integer>(t1);
            Thread t2=new Thread(ft,"新線程");
            t2.start();
            try {
                System.out.println(ft.get());
            } catch (Exception e) {
                // TODO: handle exception
            }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM