当你想要依据某些条件终结thread的时候,有两种最常见的方式。
设定标记
最常见停止thread的方式是设定某些标记来表示该thread应该要停止了。thread可以周期性地查询标记以判别它是否应该退出。如例:
package test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { Worker work = new Worker(); work.start(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { work.setDone(Boolean.parseBoolean(br.readLine())); } catch (IOException e) { e.printStackTrace(); } } } class Worker extends Thread { private volatile boolean done = false; //注意这里使用了关键词:volatile @Override public void run() { int i = 0; while(!done) { System.out.println("number: " + i++); } } /*getter,setter*/ public boolean isDone() { return done; } public void setDone(boolean done) { this.done = done; } }
时间: 2024-10-14 13:55:35