java多線程基礎實例代碼

多線程是java的一個重要特性,在網絡編程中常會用到。java中實現多線程主要有繼承Thread類實現Runnable接口兩種方法。可以直接運行的示例代碼如下:

繼承Thread類

主要包括以下幾個step:
step1.繼承Thread類,重寫run方法。
step2.創建Thread數組。
step3.創建並啓動每個Thread對象。

//多線程執行類
public class MyThread extends Thread {

    private int index; //用於向線程運行程序輸入參數。通過構造器方法輸入

    public MyThread(int index){
        this. index = index;
    }
    public void run (){
        for(int i = 0;i < 10;i ++){
            try {
                Thread.sleep(200);
            }catch(InterruptedException e ){
                continue;
            }
            System.out.println("thread:"+ index+ ":do things no."+i);
        }
    }
}
//多線程調用類
class TestThread{
    public static void main(String[] args){
        MyThread [] myThreads = new MyThread[100];
        for(int seq = 0; seq < 100; seq ++){
            myThreads[seq] = new MyThread(seq);
            myThreads[seq].start();
        }
    }
}

實現Runnable接口

主要包括以下幾個step:
step1.實現Runnable接口,重寫run方法。
step2.創建Runnable和Thread數組。
step3.傳入實現Runnbale接口的類,創建並啓動每個Thread對象。

//多線程執行類
public class MyRunnable implements Runnable{

    private int index;//用於向線程運行程序輸入參數。通過構造器方法輸入

    public MyRunnable( int index){
        this. index = index;
    }
    @Override
    public void run() {
        for(int i = 0;i < 10;i ++){
            try {
                Thread.sleep(200);
            }catch(InterruptedException e ){
                continue;
            }
            System.out.println("thread:"+ index+ ":do things no."+i);
        }
    }
}
//多線程調用類
class TestRunnable{
    public static void main(String[] args){
        MyRunnable[] myRunnables = new MyRunnable[100];
        Thread[] threads = new Thread[100];
        for(int seq = 0;seq < 100;seq ++){
            myRunnables[seq] = new MyRunnable(seq);
            threads[seq] = new Thread(myRunnables[seq]);
            threads[seq].start();
        }

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章