Java中终止线程的一种方式

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()来实现。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值