public class MainClass{
public static void main(String[] args){
Thread t = new Thread(new Runnable(){
boolean flag = false;
public void run(){
while(!flag){
try{
}catch(InterruptedException iex){
flag = true;
}
}
}});
t.start();
}
上面这段代码无法通过编译处理,编译器会提示try语句块中无法抛出InterruptedException,但是如果在try语句块中使用有关的阻塞队列等会阻塞线程的语句,则可以通过编译并且正常使用,如下面的代码就能正常通过InterruptedException来阻断线程的运行:
import java.awt.Graphics;
import java.awt.Rectangle;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import javax.swing.JFrame;
public class test{
public static void main(String[] args){
System.out.println("hit enter to terminate");
BlockingQueue<Integer> orderQueue = new LinkedBlockingQueue<>();
Seller seller = new Seller(orderQueue);
Thread[] sellerThread = new Thread[100];
for(int i =0;i<100;i++){
sellerThread[i] = new Thread(seller);
sellerThread[i].start();
}
Buyer buyer = new Buyer(orderQueue);
Thread[] buyerThread = new Thread[100];
for(int i = 0;i<100;i++){
buyerThread[i] = new Thread(buyer);
buyerThread[i].start();
}
try{
while(System.in.read()!='\n');
}catch(IOException ex){}
System.out.println("Terminating");
for(Thread t:sellerThread){
t.interrupt();
}
for(Thread t:buyerThread){
t.interrupt();
}
}
}
class Seller implements Runnable {
private BlockingQueue orderQueue;
private boolean shutdownRequest = false;
private static int id;
public Seller(BlockingQueue orderQueue) {
this.orderQueue = orderQueue;
}
public void run() {
while (!shutdownRequest) {
Integer quantity = (int) (Math.random() * 100);
try {
orderQueue.put(quantity);
System.out.println("Sell order by"
+ Thread.currentThread().getName() + ":" + quantity);
} catch (InterruptedException iex) {
shutdownRequest = true;
}
}
}
}
class Buyer implements Runnable{
private BlockingQueue orderQueue;
private boolean shutdownRequest = false;
public Buyer(BlockingQueue orderQueue) {
this.orderQueue = orderQueue;
}
public void run() {
while (!shutdownRequest) {
try {
Integer quantity = (Integer) orderQueue.take();
System.out.println("Buy order by"
+ Thread.currentThread().getName() + ":" + quantity);
} catch (InterruptedException iex) {
shutdownRequest = true;
}
}
}
}
这是一个很神奇的问题,问题出在了InterruptedException上,正常的语句无法抛出该Exception,所以一般情况下的终止线程的做法无法使用这种方式实现,具体的实现方式可以google之。或者在保证程序不会发生死锁的情况下使用stop()来实现。