Thread類的常用方法


String getName()  返回該線程的名稱。

void setName(String name)  改變線程名稱,使之與參數 name 相同。

int getPriority()   返回線程的優先級。

void setPriority(int newPriority)   更改線程的優先級。

boolean isDaemon()   測試該線程是否為守護線程。

void setDaemon(boolean on)  將該線程標記為守護線程或用戶線程。

 

static void sleep(long millis)

void interrupt()  中斷線程。

static void yield()  暫停當前正在執行的線程對象,並執行其他線程。

void join()  等待該線程終止。

void run()

void start()  

從Object類繼承來的方法  void notify()         void wait()

 

sleep阻塞

Thread.sleep(times)使當前線程從Running狀態放棄處理器進入Block狀態,休眠times毫秒,再返回Runnable狀態。

new Thread(new Runnable() {
    @Override
    public void run() {
        SimpleDateFormat format=new SimpleDateFormat("hh:mm:ss");
        //輸出系統時間的時分秒。每隔一秒顯示一次。可能會出現跳秒的情況,因為阻塞1秒過后進入runnable狀態,等待分配時間片進入running狀態后還需要一點時間
        while(true){
            try {
                Thread.sleep(1000);

            } catch (InterruptedException e) {
                 e.printStackTrace();

            }
             System.out.println(format.format(new Date()));
          }
    }
}).start();            

注意:當一個線程處於睡眠阻塞時,若被其他線程調用.interrupt方法中斷,則sleep方法會拋出InterruptedException異常

public static void main(String[] args) {
        /*
         * 表演者:處於睡眠阻塞的線程。
         * 當一個方法中的局部內部類中需要引用該方法的其他局部變量,那么這個變量必須是final的
         */
        final Thread lin = new Thread() {
            public void run() {
                System.out.println("林:剛美完容,睡覺吧!");
                try{
                    // 當一個線程處於睡眠阻塞時,若被其他線程調用interrupt()方法中斷,則sleep()方法會拋出 InterruptedException異常
                    Thread.sleep(100000000);
                }
                catch(InterruptedException e){
                    System.out.println("林:干嘛呢!都破了相了!");
                }
            }
        };
        /*
         * 表演者:中斷睡眠阻塞的線程
         */
        Thread huang = new Thread() {
            public void run() {
                System.out.println("黃:開始砸牆!");
                for(int i = 0; i < 5; i++){
                    System.out.println("黃:80!");
                    try{
                        Thread.sleep(1000);
                    }
                    catch(InterruptedException e){
                    }
                }
                System.out.println("咣當!");
                System.out.println("黃:搞定!");

                // 中斷lin的睡眠阻塞
                lin.interrupt();
            }
        };
        lin.start();
        huang.start();
}

 

后台線程

后台線程的特點:用法與前台線程無異,只是當一個進程中所有前台線程都結束后,無論后台線程是否還處於運行中都將被強制結束,從而使得進程結束程序退出。

后台線程也稱為:守護線程。精靈線程。

在運行程序時,操作系統會啟動一個進程來運行jvm,jvm運行后會創建第一個前台線程來運行我們程序的main方法。同時也會創建一個后台線程運行GC。

public static void main(String[] args) {

        // Rose,表演者:前台線程
        Thread rose = new Thread() {
            public void run() {
                for(int i = 0; i < 10; i++){
                    System.out.println("rose:let me go!");
                    try{
                        Thread.sleep(1000);
                    }
                    catch(InterruptedException e){
                        e.printStackTrace();
                    }
                }
                System.out.println("rose:啊啊啊啊AAAAAAaaaaaa....");
                System.out.println("噗通!");
            }
        };

        // jack,表演者:后台線程
        Thread jack = new Thread() {
            public void run() {
                while(true){
                    System.out.println("jack:you jump!i jump!");
                    try{
                        Thread.sleep(1000);
                    }
                    catch(InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }
        };

        /*
         * 設置為后台線程
         * 設置后台線程的方法要在該線程被調用start()方法之前調用
         */
        jack.setDaemon(true);
        rose.start();
        jack.start();
}

 

線程的優先級

優先級被划分為1-10,1最低10最高。優先級越高的線程被分配時間片的機會越多,那么被CPU執行的機會就越多。

public static void main(String[] args) {
        // 最高優先級的線程
        Thread max = new Thread() {
            public void run() {
                for(int i = 0; i < 1000; i++){
                    System.out.println("max");
                }
            }
        };
        // 最低優先級的線程
        Thread min = new Thread() {
            public void run() {
                for(int i = 0; i < 1000; i++){
                    System.out.println("min");
                }
            }
        };
        // 默認優先級的線程
        Thread norm = new Thread() {
            public void run() {
                for(int i = 0; i < 1000; i++){
                    System.out.println("norm");
                }
            }
        };
        // void setPriority(int p),設置當前線程的優先級, 最高,最低,默認都有常量對應。
        // 設置了優先級也不能100%控制線程調度。只是最大程度的告知線程調度以更多的幾率分配時間片給線程優先級高的線程
        max.setPriority(Thread.MAX_PRIORITY);
        min.setPriority(Thread.MIN_PRIORITY);
        // 這項設置可以省略,默認情況下就是該值
        norm.setPriority(Thread.NORM_PRIORITY);

        min.start();
        norm.start();
        max.start();
}

 

 

join方法

/**
 * 線程的協同工作 join方法
 */
public class Demo {

    // 判斷照片是否下載完成
    public static boolean isFinish = false;

    public static void main(String[] args) {
        // 下載圖片的線程
        final Thread download = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("download:開始下載圖片");
                for(int i = 0; i <= 100; i++){
                    System.out.println("download:已完成" + i + "%");
                    try{
                        Thread.sleep(50);
                    }
                    catch(InterruptedException e){
                        e.printStackTrace();
                    }
                }
                System.out.println("download:圖片下載完畢");
                isFinish = true;
            }
        });
        download.start();

        // 用於顯示圖片的線程
        Thread showImg = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("show:准備顯示圖片");
                // 等待下載線程工作結束后,再執行下面的代碼,
                try{
                    // 此時顯示圖片的線程就進入阻塞狀態,等待download線程運行結束,才能執行下面的代碼。注意千萬不要在永遠也死不了的線程上等待
                    download.join();
                }
                catch(InterruptedException e){
                    e.printStackTrace();
                }
                if(!isFinish){
                    throw new RuntimeException("show:圖片還沒有下載完");
                }
                System.out.println("show:圖片顯示完成!");
            }
        });
        showImg.start();
    }

}

 

wait()notify()方法

/**
 * 使用wait()與notify()方法完成線程協同工作
 */
public class Demo {

    public static boolean isFinish = false;
    public static Object object = new Object();

    public static void main(String[] args) {

        // 下載圖片的線程
        final Thread download = new Thread() {
            public void run() {
                System.out.println("download:開始下載圖片");
                for(int i = 0; i <= 100; i++){
                    System.out.println("download:已完成" + i + "%");
                    try{
                        Thread.sleep(50);
                    }
                    catch(InterruptedException e){
                    }
                }
                System.out.println("download:圖片下載完畢");
                isFinish = true;// 表示圖片下載完畢了

                // 當圖片下載完畢后,就可以通知showImg開始顯示圖片了
                synchronized(object){
                    // 通知在object身上等待的線程解除等待阻塞
                    object.notify();
                }

                System.out.println("download:開始下載附件");
                for(int i = 0; i <= 100; i++){
                    System.out.println("download:已完成" + i + "%");
                    try{
                        Thread.sleep(50);
                    }
                    catch(InterruptedException e){
                    }
                }
                System.out.println("download:附件下載完畢");
            }

        };

        // 用於顯示圖片的線程
        Thread showImg = new Thread() {
            public void run() {
                System.out.println("show:准備顯示圖片");
                // 等待下載線程將圖片下載結束后,再執行下面的代碼
                try{
                    // wait()阻塞會在以下兩種情況被解除,1:當download線程結束. 2:當調用了download的notify()
                    synchronized(object){
                        object.wait();
                    }
                }
                catch(InterruptedException e){
                    e.printStackTrace();
                }
                if(!isFinish){
                    throw new RuntimeException("圖片沒有下載完畢");
                }
                System.out.println("show:圖片已經顯示了!");
            }
        };

        download.start();
        showImg.start();
    }
}

 


免責聲明!

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



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