多執行緒——停止執行緒(結束run方法)
阿新 • • 發佈:2018-12-26
package com.qianfeng.demo01; /** * 停止執行緒: * 1.stop():已過時,這種方法有固有的不安全性,強制停止執行緒,不論處於什麼狀態都會停止,就會導致執行緒的不安全。 * 2.run方法結束了,當執行緒中沒有執行的程式碼時,執行緒就結束了,意味著任務結束,執行緒消失。 * * 考慮一個問題,怎麼能讓run方法結束呢? * 一般情況下,run方法當中都會定義迴圈。 * 原因: * 開啟新的執行路徑是為了讓多次運算和其他程式碼進行同時的執行。 * * public void run(){ * syso("hello world"); //這個執行緒任務是毫無意義的,不需要開啟執行緒。 * } * * public void run(){ * while(true){ * syso("hello world"); * } * } * * 開啟多執行緒會同時重複的做很多運算。 * * 怎麼結束run方法呢? 控制run方法當中的迴圈就可以了。 * 怎麼控制迴圈呢? 在迴圈當中設定標誌位,通過標誌位來完成。 * */ class StopRun implements Runnable{ private boolean flag = true; public void setFlag(boolean flag) { this.flag = flag; } @Override public void run() { while (flag) { System.out.println(Thread.currentThread().getName()+".....run"); } } } public class StopThreadDemo01 { public static void main(String[] args) { StopRun sRun = new StopRun(); Thread t1 = new Thread(sRun); Thread t2 = new Thread(sRun); t1.start(); t2.start(); int num = 0; while (true) { if (++num==50) { sRun.setFlag(false); break; } System.out.println(Thread.currentThread().getName()+".....run.."+num); } System.out.println("over"); } }