Java- 如何實現多線程?


1、繼承Thread 類,重寫run 方法

public class TestCreateThread{
    public static void main(String args[]){
        MyThread t = new MyThread();
        t.start();
        for(int i = 0;i<100;i++){
            System.out.println("main");
        }
    }
    
}

class MyThread extends Thread{
    public void run(){
        for(int i = 0;i<100;i++){
            System.out.println("thread");
        }
        
    }

}

2、實現runnable 接口,實現run() 方法

public class TestCreateThread{
    public static void main(String args[]){
        MyThread1 t1 = new MyThread1();
        t1.start();
        
        MyThread2 r = new MyThread2();
        Thread t2 = new Thread(r);
        t2.start();
        
        for(int i = 0;i<1000;i++){
            System.out.println("Main");
        }
    }
}

class MyThread1 extends Thread{
    public void run(){
        for(int i = 0;i<1000;i++){
            System.out.println("Thread");
        }
        
    }

}

class MyThread2 implements Runnable{
    public void run(){
        for(int i = 0;i<1000;i++){
            System.out.println("Runnable");
        }
    }
}

3、實現 Callable 接口,重寫call() 方法

不太會

 

 

ps.注意的是 線程對象不要直接調run()方法。直接調,run()就是普通方法,實現多線程,需要調start()方法,然后由jvm 去調用run()方法。


免責聲明!

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



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