通常情况下, 我们要阻止线程运行是在run方法中添加if判断来决定是否让线程继续运行, 今天在一个同事的帮助下, 我们使用另一种方式来结束线程, 即线程池的方式。下面首先看第一种方法的例子:
运行代码输出结果
第二种方法的例子:
运行结果
这两种方法的用处各有各的特点,线程池可以用于计时器等程序中,请自行揣摩。
public class ThreadTest {
private static int counter;
private static final int MAX_VALUE = 5;
public static void main(String[] args) throws InterruptedException {
Thread mThread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
if (counter == MAX_VALUE) {
System.out.println("Counter is 5 now");
break;
} else {
++counter;
System.out.println("Counter= " + counter);
}
}
}
});
mThread.start();
mThread.join();
if (mThread.isAlive()) {
System.out.println("Thread is still alive");
} else {
System.out.println("Thread is dead! ");
mThread = null;
}
}
}
运行代码输出结果
Counter= 1
Counter= 2
Counter= 3
Counter= 4
Counter= 5
Counter is 5 now
Thread is dead!
第二种方法的例子:
public class ThreadPoolTest {
private static ScheduledExecutorService schedule;
private static int counter;
private static final int MAX_VALUE = 5;
public static void main(String[] args) throws InterruptedException {
addTask();
}
public static void addTask() throws InterruptedException {
schedule = Executors.newScheduledThreadPool(1);
schedule.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
System.out.println("Count = " + counter);
++counter;
if (counter == MAX_VALUE) {
if (!schedule.isShutdown()) {
schedule.shutdown();
}
}
}
}, 1, 1, TimeUnit.SECONDS);
Thread.sleep(10000);
if (schedule.isTerminated()) {
System.out.println("Thread pool is terminated");
} else {
System.out.println("Thread pool is not still terminated");
}
schedule = null;
}
}
运行结果
Count = 0
Count = 1
Count = 2
Count = 3
Count = 4
Thread pool is terminated
这两种方法的用处各有各的特点,线程池可以用于计时器等程序中,请自行揣摩。