Java终止线程
Thread提供了stop()方法終止線程,但是該方法是強(qiáng)行終止,容易產(chǎn)生一些錯(cuò)誤,已經(jīng)被廢棄。
可以使用退出標(biāo)志來終止線程,在run()函數(shù)里面設(shè)置while循環(huán),把退出標(biāo)志作為while的條件,當(dāng)條件為false時(shí),run函數(shù)執(zhí)行完畢,線程就自動(dòng)終止了。
package com.my_code.thread;public class MyThread extends Thread {public volatile boolean isRunning = true; public void run(){while (isRunning){try {sleep(5000);} catch (InterruptedException e) {// TODO Auto-generated catch block e.printStackTrace();}}}public void stopIt(){isRunning = false;}public static void main(String[] args) throws InterruptedException{MyThread thread = new MyThread();thread.start();sleep(10000);thread.stopIt();thread.join();System.out.println("線程已經(jīng)退出!"); }}總結(jié)
- 上一篇: 解决linux yum无法安装mysql
- 下一篇: Java千百问_03基本语法(002)_