溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java多線程Thread怎么創(chuàng)建

發(fā)布時(shí)間:2023-05-06 10:23:14 來源:億速云 閱讀:111 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“Java多線程Thread怎么創(chuàng)建”的相關(guān)知識(shí),小編通過實(shí)際案例向大家展示操作過程,操作方法簡單快捷,實(shí)用性強(qiáng),希望這篇“Java多線程Thread怎么創(chuàng)建”文章能幫助大家解決問題。

    1. 創(chuàng)建線程   

    1.1 通過構(gòu)造函數(shù):public Thread(Runnable target, String name){}  或:public Thread(Runnable target){}

    示例:

    Thread thread1 = new Thread(new MyThread(), "mythread");
    class MyThread extends Thread(){
            public void run(){
                 System.out.println("My First Thread');
            }
    }

    1.2 直接實(shí)現(xiàn)Runnable接口:

    示例:

    Thread thread2 = new Thread(new Runnable{}{
             public void run(){
                      System.out.println("This is my thread.");
              }
    });

    2. 運(yùn)行線程   

    thead1.start()    

     3. sleep

    try{
        #休眠1000ms
        Thread.sleep(1000);
    }catch(InterruptedException e){
        e.printStackTrace();
    }

    4. getName() 獲取線程名字, getId()獲取線程id

    System.out.println(Thread.currentThread().getName() + ":"+ Thread.currentThread().getId);

    5. 停止線程,

    千萬不用stop(),stop會(huì)立即終止線程。

    通過interrupt()中斷線程,但是中斷并沒有停止線程,配合異常來實(shí)現(xiàn):

    public class Main {
       public static void main(String[] args) throws InterruptedException {
          try{
              Thread thread1=new Thread(new TheThread(),"thread1");
              thread1.start();
              Thread.sleep(2000);
              thread1.interrupt();
          }catch (InterruptedException e){
                      e.printStackTrace();
           }
       }
    }
       class TheThread extends Thread{
         public void run() {
            super.run();
            for (int i = 0; i < 10; i++) {
               if(this.interrupted()){
                  break;
            }
            System.out.println(Thread.currentThread().getName() + ":" + i);
         }
       }
    }

    注意,如果在TheThread類里加入catch InterruptException的話,可能會(huì)導(dǎo)致interrupt被捕獲,而繞過if(this.interrupted())的判斷而無法終止線程。

    6. 等待和通知        

    線程等待:當(dāng)前線程就處于等待狀態(tài),直到其他線程調(diào)用了notify()方法,線程才會(huì)繼續(xù)執(zhí)行

    public final void wait() throws InterruptedException

    線程通知:

    public final native void notify()

    注意:在notify()方法后,當(dāng)前線程不會(huì)馬上釋放該對(duì)象鎖,要等到執(zhí)行notify()方法的線程將程序執(zhí)行完,也就是退出同步代碼塊中。

     package wait.notify;
     
     public class ThreadWaitNotifyTest {
         final static Object object=new Object();
         public static class T1 extends Thread{
             public void run(){
                 System.out.println(System.currentTimeMillis()+": T1 start");
                 synchronized (object){
                     try {
                         System.out.println(System.currentTimeMillis()+": T1 wait");
                         object.wait();
                     } catch (InterruptedException e) {
                         e.printStackTrace();
                     }
                 }
                 System.out.println(System.currentTimeMillis()+": T1 end");
             }
         }
         public static class T2 extends Thread{
             public void run(){
                 System.out.println(System.currentTimeMillis()+": T2 start");
                 synchronized (object){
                     System.out.println("T2 synchonized code start.");
                     object.notify();
                     try {
                         Thread.sleep(2000);
                     } catch (InterruptedException e) {
                         e.printStackTrace();
                     }finally{
                         System.out.println("T2 synchonized code end.");
                     }
     
                 }
                 try {
                     Thread.sleep(2000);
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
                 System.out.println(System.currentTimeMillis()+": T2 end");
             }
         }
         public static void main(String[] args){
             Thread thread1=new T1();
             Thread thread2=new T2();
             thread1.start();
             thread2.start();
         }
     }

    輸出結(jié)果:

    Java多線程Thread怎么創(chuàng)建

    7. 線程優(yōu)先級(jí)

    高優(yōu)先級(jí)的線程將會(huì)獲得更多的CPU資源。一共分為10個(gè)優(yōu)先級(jí)。

    public final void setPriority(int newPriority)

    源碼分析:

    public final void setPriority(int newPriority) {
            ThreadGroup g;
            checkAccess();
            if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
                throw new IllegalArgumentException();
            }
            if((g = getThreadGroup()) != null) {
                if (newPriority > g.getMaxPriority()) {
                    newPriority = g.getMaxPriority();
                }
                setPriority0(priority = newPriority);
            }
    }
    public final static int MIN_PRIORITY = 1;
    public final static int NORM_PRIORITY = 5;
    public final static int MAX_PRIORITY = 10;

    可見線程最高優(yōu)先級(jí)為10, 最低為1, 默認(rèn)為5.

    當(dāng)設(shè)定的newPriority高于該線程組ThreadGroup的最高Priority時(shí),只能分配該線程組的最高Priority

    8. 守護(hù)線程

    類似守護(hù)進(jìn)程,Java存在兩種線程:用戶線程和守護(hù)線程。它是一種特殊線程,執(zhí)行的是一種后臺(tái)服務(wù),當(dāng)一個(gè)系統(tǒng)中不存在非守護(hù)線程的時(shí)候,守護(hù)線程會(huì)自己銷毀。典型的守護(hù)線程:JVM的垃圾回收線程。

    public final void setDaemon(boolean on)

    示例:

    public class Main {
        public static void main(String[] args) throws InterruptedException {
           TheThread theThread=new TheThread();
            theThread.setDaemon(true);//設(shè)置守護(hù)線程
            theThread.start();
            Thread.sleep(5000);
            System.out.println("全都退出啦");
        }
        public static class TheThread extends Thread{
            public void run(){
                int i = 0;
                while (true){
                    i++;
                    System.out.println(Thread.currentThread().getId()+":"+i);
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    源碼分析:

    設(shè)置線程為用戶線程(user thread)或守護(hù)線程(daemon thread),當(dāng)剩余運(yùn)行的線程均為守護(hù)線程時(shí),JVM會(huì)退出。

     public final void setDaemon(boolean on) {
            checkAccess();
            if (isAlive()) {
                throw new IllegalThreadStateException();
            }
            daemon = on;
        }

    其中checkAccesss()方法如下:

     public final void checkAccess() {
            SecurityManager security = System.getSecurityManager();
            if (security != null) {
                security.checkAccess(this);
            }
        }

    該方法用于判斷當(dāng)前運(yùn)行的線程是否有修改此線程的權(quán)限。

    而public final native boolean isAlive();用于判斷該線程是否處于alive狀態(tài),即該線程是否已經(jīng)start,且沒有die。

    當(dāng)isAlive的話就會(huì)拋出IllegalThreadStateException異常。

    所以,設(shè)置守護(hù)線程的方法,邏輯就是先判斷當(dāng)前線程是否有修改的權(quán)限,再判斷是否處于alive狀態(tài),如果不處于alive狀態(tài),則根據(jù)boolean變量on的值更改它的狀態(tài),即true:設(shè)為daemon線程,false:設(shè)為user線程。

    關(guān)于“Java多線程Thread怎么創(chuàng)建”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí),可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會(huì)為大家更新不同的知識(shí)點(diǎn)。

    向AI問一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI