多線程

1.是什么?

  • 多線程,是一個(gè)進(jìn)程同一時(shí)間段,執(zhí)行多個(gè)代碼段
  • 為了盡可能的利用系統(tǒng)資源。
  • 線程執(zhí)行過(guò)程:
    創(chuàng)建 new Thread();
    就緒 new Thread().start();
    阻塞 new Thread().sleep(400);
    運(yùn)行 繼承Thread方法時(shí)extends Thread;需重寫(xiě)的代碼run()方法
    死亡 new Thread().stop();

2.怎么做?

繼承thread類(lèi)
class ThreadExtends extends Thread {
    private String name;
    
    public ThreadExtends(String name){
        this.name = name;
    }
    
    public void run(){ //運(yùn)行
        for(int i=0; i<10; i++){
            System.out.println(this.name+" : "+i);
        }
    }
}

public class testDemo{
    public static void main(String arg[]){
        ThreadExtends thread1 = new ThreadExtends("thread1");//創(chuàng)建
        ThreadExtends thread2 = new ThreadExtends("thread2");
        thread1.start();//就緒
        thread2.start();
    }
}

extends Thread運(yùn)行結(jié)果:

thread1 : 0
thread1 : 1
thread1 : 2
thread1 : 3
thread2 : 0
thread2 : 1
thread2 : 2
thread2 : 3
thread2 : 4
thread2 : 5
thread2 : 6
thread2 : 7
thread2 : 8
thread2 : 9
thread1 : 4
thread1 : 5
thread1 : 6
thread1 : 7
thread1 : 8
thread1 : 9


實(shí)現(xiàn)Runnable接口
class ThreadImplements implements Runnable {
    private String name;
    
    public ThreadImplements(String name){
        this.name = name;
    }
    
    public void run(){
        for(int i=0; i<10; i++){
            System.out.println(this.name+" : "+i);
        }
    }
}

public class testDemo{
    public static void main(String arg[]){
        ThreadImplements threadImp1 = new ThreadImplements("thread1");
        ThreadImplements threadImp2 = new ThreadImplements("thread2");
        Thread thread1 = new Thread(threadImp1);
        Thread thread2 = new Thread(threadImp2);
        thread1.start();
        thread2.start();
    }
}

implements Runnable運(yùn)行結(jié)果:

thread2 : 0
thread2 : 1
thread2 : 2
thread2 : 3
thread2 : 4
thread2 : 5
thread2 : 6
thread2 : 7
thread2 : 8
thread2 : 9
thread1 : 0
thread1 : 1
thread1 : 2
thread1 : 3
thread1 : 4
thread1 : 5
thread1 : 6
thread1 : 7
thread1 : 8
thread1 : 9

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容