Java 提供了中断几只,我们可以使用它来结束一个线程。这种机制要求线程检查它是否被中断了,然决定是不是响应这个中断请求,或者继续执行。
范例:打印质数,2秒后结束
方法一:手动控制
package com.rr.concurrent.chapter1.recipe3.test;
/**
* Created by isaac_gu on 2016/5/10.
*/
public class Task implements Runnable {
@Override
public void run() {
Thread thread = Thread.currentThread();
int i = 0;
while (i++ >= 0) {
if (thread.isInterrupted()) {
System.out.println("线程被打断了!");
//return;
System.exit(0);
} else if (isPrime(i)) {
System.out.printf("%d 是 质数\r\n", i);
}
}
}
/**
* 百度百科的实现方法
*
* @param n
* @return
*/
public static boolean isPrime(long n) {
if (n <= 3) {
return n > 1;
}
if (n % 2 == 0 || n % 3 == 0) {
return false;
}
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
}
测试:
package com.rr.concurrent.chapter1.recipe3.test;
import java.util.concurrent.TimeUnit;
/**
* Created by isaac_gu on 2016/5/10.
* 打印质数,2秒后结束
*/
public class Test {
public static void main(String[] args) {
Thread thread = new Thread(new Task());
thread.start();
//睡眠2秒
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
//2秒后打断
thread.interrupt();
}
}
检查线程是否被中断的方法有两种: isInterrupted() 和 静态方法Thread.interrupted();
方法二: 使用异常
package com.rr.current2.c1_3_interruptException.test;
/**
* Created by Isaac on 16-5-10.
*/
/**
* Created by isaac_gu on 2016/5/10.
*/
public class Task implements Runnable {
@Override
public void run() {
try {
print();
} catch (InterruptedException e) {
System.out.printf("%s: 线程被打断了!", Thread.currentThread().getName());
}
}
public void print() throws InterruptedException {
int i = 0;
while (i++ >= 0) {
if(Thread.interrupted()){
throw new InterruptedException();
} else if (isPrime(i)) {
System.out.printf("%d 是 质数\r\n", i);
}
}
}
/**
* 百度百科的实现方法
*
* @param n
* @return
*/
public static boolean isPrime(long n) {
if (n <= 3) {
return n > 1;
}
if (n % 2 == 0 || n % 3 == 0) {
return false;
}
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
}