Wellcom to my Blog for Javascript

java的线程中断

在java中中断线程可以使用interrupt()函数。此函数虽然不能终止线程的运行,但是可以改变线程的状态为true

即:isInterrupted()的值返回为true

注意:当函数调用了已经被阻塞的线程后,被阻塞的线程将会接收到一个InterruptedException异常。即当前线程即可终止。

例如:

package TestThread.ThreadSynchronized;

public class TestWaitAll {
	public static void main(String[] args) {
		// 创建线程对象
		Test1 test1 = new Test1();
		// 创建线程
		Thread t = new Thread(test1, "线程1");
		Thread t1 = new Thread(test1, "线程2");
		Thread t2 = new Thread(test1, "线程3");
		Thread t3 = new Thread(test1, "线程4");
		// 这是唤醒线程
		Test2 test2 = new Test2(test1, "唤醒线程");
		t.start();
		t1.start();
		t2.start();
		t2.interrupt();// 中断线程
		t3.start();
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// 启动唤醒线程
		test2.start();
	}
}

class Test1 implements Runnable {
	public void run() {
		synchronized (this) {
			// 当被阻塞的线程调用了interrupt后将会发生异常
			try {
				this.wait();
				System.out.println(Thread.currentThread().getName() + ":我没有被中断,我可以执行到!");
			} catch (InterruptedException e) {
				System.out.println(Thread.currentThread().getName() + ":被中断了!");
			}
		}
	}
}

/**
 * @author CHAI015 生成唤醒类
 */
class Test2 extends Thread {
	/**
	 * Test1 为唤醒对象 name 为线程名称
	 */
	private Test1 test1;
	String name;

	/**
	 * @param test1唤醒对象
	 * @param name唤醒名称
	 */
	public Test2(Test1 test1, String name) {
		super(name);
		this.name = name;
		this.test1 = test1;
	}

	public void run() {
		synchronized (test1) {
			test1.notifyAll();// 针对当前对象执行唤醒所有线程的操作
			System.out.println(Thread.currentThread().getName() + ":唤醒线程执行成功!");
		}
	}
}

运行结果为:

 

posted on 2017-03-24 11:44  温柔的鲨鱼  阅读(301)  评论(0编辑  收藏  举报

导航