2023年java多線程示例大全

字號:

    在日常的學(xué)習(xí)、工作、生活中,肯定對各類范文都很熟悉吧。寫范文的時(shí)候需要注意什么呢?有哪些格式需要注意呢?以下是我為大家搜集的優(yōu)質(zhì)范文,僅供參考,一起來看看吧
    java多線程示例篇一
     java多線程實(shí)現(xiàn)方式主要有三種:繼承thread類、實(shí)現(xiàn)runnable接口、使用executorservice、callable、future實(shí)現(xiàn)有返回結(jié)果的多線程,以下是小編為大家搜索整理的java多線程,歡迎閱讀!更多精彩內(nèi)容請及時(shí)關(guān)注我們應(yīng)屆畢業(yè)生考試網(wǎng)!
     多線程的基本實(shí)現(xiàn)
     進(jìn)程指運(yùn)行中的程序,每個(gè)進(jìn)程都會(huì)分配一個(gè)內(nèi)存空間,一個(gè)進(jìn)程中存在多個(gè)線程,啟動(dòng)一個(gè)java虛擬機(jī),就是打開個(gè)一個(gè)進(jìn)程,一個(gè)進(jìn)程有多個(gè)線程,當(dāng)多個(gè)線程同時(shí)進(jìn)行,就叫并發(fā)。
     java創(chuàng)建線程的兩種方式為: 繼承thread類 和實(shí)現(xiàn)runnable接口
     thread類
     1、通過覆蓋run方法實(shí)現(xiàn)線程要執(zhí)行的程序代碼
     2、start()開始執(zhí)行多線程
     package ncheng;
     public class d1 extends thread{
     public void run(){
     for(int i=0 ; i<50; i++){
     n(i);
     n(currentthread()。getname());
     try {
     sleep(100);
     } catch (interruptedexception e) {
     // todo auto-generatedcatch block
     tacktrace();
     }
     }
     }
     public static void main(string[] args){
     new d1()。start();
     new d1()。start();
     }
     }
     多個(gè)線程共享一個(gè)實(shí)例的時(shí)候,代碼代碼如下:
     package ncheng;
     public class d1 extends thread{
     int i=0;
     public void run(){
     for(i=0 ; i<50; i++){
     n(i);
     n(currentthread()。getname());
     try {
     sleep(100);
     } catch (interruptedexception e) {
     // todo auto-generatedcatch block
     tacktrace();
     }
     }
     }
     public static void main(string[] args){
     new d1()。start();
     new d1()。start();
     }
     }
     結(jié)果如下所示:
     0
     thread-1
     0
     thread-0
     1
     thread-1
     1
     實(shí)際2個(gè)線程在操縱不同的.變量a,在執(zhí)行run方法時(shí)候,線程把a(bǔ)都當(dāng)做自己的變量在執(zhí)行。
     runnable接口實(shí)現(xiàn)多線程
     當(dāng)一個(gè)繼承自thread時(shí),就不能再繼承其他類,使用runnable接口解決了此問題,在新建一個(gè)thread類中,在構(gòu)造方法中初始化
     thread(runnable target)
     分配新的 thread 對象。
     thread(runnable target,string name)
     分配新的 thread 對象。
     package ncheng;
     public class d2 implements runnable{
     int i=0;
     public void run(){
     for(i=0 ; i<50; i++){
     n(i);
     n(tthread()。getname());
     try {
     (100);
     } catch (interruptedexception e) {
     // todo auto-generatedcatch block
     tacktrace();
     }
     }
     }
     public static void main(string[] args){
     d2 d=new d2();
     thread t=new thread(d);
     ();
     }
     }
    s("content_relate");
    【java多線程】相關(guān)文章:
    1.java多線程介紹
    2.java多線程教程
    3.關(guān)于java多線程介紹
    4.淺談如何使用java多線程
    5.java多線程的開發(fā)技巧
    6.java多線程的基本使用
    7.40個(gè)java多線程問題總結(jié)
    8.java多線程的定義狀態(tài)和屬性
    9.java多線程同步塊實(shí)例講解素材