join()方法和中斷線程

中斷線程:

       自定義標記的方式
  

package com.vince;

/**
 * Thread.currentThread():獲取當前線程
 * 中斷線程:
 *      自定義標記的方式
 */
public class ThreadDemo2 {
    public static void main(String[] args) {
        //實現runable接口:  沒有開闢線程的能力,要將創建的對象交給指定線程來運行
        MyRunnable3 mr3 = new MyRunnable3();
        Thread t1 = new Thread(mr3);
        t1.start();

        for(int i = 0; i < 10; i++){
            System.out.println(Thread.currentThread().getName()+"--"+i);
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(i == 5){
                mr3.flag = false;
            }
        }
    }
}

class  MyRunnable3 implements  Runnable{
    public boolean flag = true;
    public MyRunnable3(){
           flag = true;
    }
    @Override
    public void run() {
        int i = 0;
        while (flag){
            System.out.println(Thread.currentThread().getName()+"####"+(i++));
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

                       

join方法:
       加入線程,讓調用的線程先執行,指定時間或執行完畢

package com.vince;

/**
 * Thread.currentThread():獲取當前線程
 * join方法:
 *     加入線程,讓調用的線程先執行,指定時間或執行完畢
 */
public class ThreadDemo2 {
    public static void main(String[] args) {
        //實現runable接口:  沒有開闢線程的能力,要將創建的對象交給指定線程來運行
        MyRunnable2 mr2 = new MyRunnable2();
        Thread t = new Thread(mr2);
        t.start();

        for(int i = 0; i < 10; i++){
            System.out.println(Thread.currentThread().getName()+"--"+i);
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(i == 5){
                try {
                    t.join();//讓t線程執行完畢
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
             }
        }
    }
}

class MyRunnable2 implements Runnable{
    @Override
    public void run() {
        for(int i = 0; i < 10; i++){
           System.out.println(Thread.currentThread().getName()+"--"+i);
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
         }
        }
    }
}

                                   

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章