Java 线程池

通常情况下, 我们要阻止线程运行是在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


这两种方法的用处各有各的特点,线程池可以用于计时器等程序中,请自行揣摩。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值