您的位置:首页 > 编程语言 > Java开发

Java中的线程中断

2014-04-22 22:50 218 查看
1、线程的状态:

1)新建(new):线程被创建之后,已经执行了初始化,系统也为线程分配了各种所需的资源,只要获得cpu,线程既可以开始执行;

2)就绪(Runnable):此时,线程虽然处于Runnable状态,但是它不一定正在运行,只有当线程获得了cpu时间片才真正的在运行,系统给线程分配的时间片没办法控制;

3)阻塞(Blocked):线程能够运行,但是某种条件阻止了它的运行,此时,线程调度器不会再将cpu时间片分配给处于该状态下的线程,直到线程重新进入就绪状态;

4)死亡(Dead):线程被中断或者从run方法返回。

2、导致线程进入阻塞状态的原因:

1)调用sleep()、wait()、join()方法;

2)线程在等待I/O操作的完成;

3)线程在等待获得同步锁。

3、线程的中断状态:

interrupt status,也即中断状态,true表示线程被中断了,false表示没有被中断。在Java API中表示中断状态的字段是:private
volatile Interruptible blocker;对“Interruptible”这个类不需要深入分析,对于“blocker”变量有以下几个操作:

1)默认的blocker = null;

2)interrupt0()方法将会导致线程的中断状态被设置为true;

3)再次调用interrupt0()方法将导致线程的中断状态被清除(中断状态变成false)。

4、线程中断相关的方法:

1)public void interrupt():

public void interrupt() {
if (this != Thread.currentThread())
checkAccess();

synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
interrupt0();           // Just to set the interrupt flag
b.interrupt(this);
return;
}
}
interrupt0();
}


这个方法并没有直接中断线程,只是设置了线程的中断状态为true(同步快的后面调用了interrupt0()方法)。同步块中的if语句在默认情况下并不会执行,因为b(也就是中断状态)默认情况下是null。如果线程调用了sleep()、wait()、join()方法而使线程进入阻塞状态(b != null),interrupt()方法会清除中断状态(同步快中调用了一次interrupt0()方法),并抛出InterruptedException异常;

2)public static boolean interrupted():

public static boolean interrupted() {
return currentThread().isInterrupted(true);
}


返回线程前一次的中断状态,返回之后,线程的中断状态会被设置为false;

3)public boolean isInterrupted():

public boolean isInterrupted() {
return isInterrupted(false);
}


返回线程当前的中断状态,与2)不同的是,这个方法并不会清除线程的中断状态。(一般使用这个方法来检查线程的中断状态)

4)private native boolean isInterrupted(boolean ClearInterrupted)

检查线程是否被中断,线程的中断状态会被重新设置为传进去的状态。(这个方法因为是private型的,所以没法调用)

注:

a、这里所说的线程的中断跟操作系统中的中断(进程因为分配的CPU时间片用完而放弃CPU)不是一个概念;

b、异常并不是由引起中断的方法抛出的,而是由前面说的sleep、wait、join方法抛出的;

c、线程的中断状态被设置为true之后,线程是否抛出中断异常,由线程自己来决定。正常运行的线程不会抛出中断异常,阻塞的线程会抛出中断异常;

5、代码1:几种类型的中断

说明:下面的每一个类都代表一种类型的中断

class SleepBlocked implements Runnable {

@Override
public void run() {
// TODO Auto-generated method stub
try {
System.out.println("SleepBlocked线程休眠中...");
TimeUnit.SECONDS.sleep(100);// 线程休眠100秒
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("SleepBlocked线程休眠期间被中断");
}
}
}

class JoinBlocked implements Runnable {

@Override
public void run() {
// TODO Auto-generated method stub
try {
System.out.println("JoinBlocked等待子线程执行完毕...");
new JoinThread().join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("JoinBlocked线程等待子线程执行期间被中断");
}
}

class JoinThread extends Thread {

public JoinThread() {
start();
}

public void run() {
// TODO Auto-generated method stub
while (true)
// 中间插进来的进程一直不退出,使外层的线程一直处于阻塞状态
Thread.yield();
}
}

}

class IOBlocked implements Runnable {
private InputStream in;

public IOBlocked(InputStream is) {
in = is;
}

@Override
public void run() {
// TODO Auto-generated method stub
try {
System.out.println("IOBlocked线程等待输入...");
in.read(); // 这个方法也会产生阻塞,等待输入完成
} catch (IOException e) {
if (Thread.currentThread().isInterrupted()) {
System.out.println("IOBlocked线程等待输入期间被中断");
} else {
throw new RuntimeException(e);
}
}
}
}

class SynchronizedBlocked implements Runnable {

public synchronized void f() {
while (true)
Thread.yield();
}

public SynchronizedBlocked() {
new Thread() {
public void run() {
f(); // 此处的f()方法会在run()中的f()方法之前执行
}
}.start();
}

@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("SynchronizedBlocked线程等待获取同步锁...");
f(); // 此处的f()方法会一直处于阻塞状态,等待获得同步锁,当然,它永远也不会获得同步锁
}
}

class RunningThread implements Runnable {
boolean flag = true;

@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("RunningThread线程正常执行中...");
while (flag)
// 为了骗编译器,在这个地方不能用true代替flag
Thread.yield();
System.out.println("RunningThread执行过程中被中断");
}

}

class InterruptedThread implements Runnable {

boolean flag = true;

@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("InterruptedThread线程正常执行中...");
while (flag)
// 为了骗编译器,在这个地方不能用true代替flag
Thread.yield();
System.out.println("InterruptedThread执行过程中被中断");
}

}

public class ThreadInterrupting {
private static ExecutorService exec = Executors.newCachedThreadPool();

static void test_cancel(Runnable r)
throws InterruptedException {
Future<?> f = exec.submit(r);
TimeUnit.MILLISECONDS.sleep(100);
f.cancel(true);
}

static void test_interrupt(Runnable r)
throws InterruptedException {
Thread thread = new Thread(r);
thread.start();
TimeUnit.MILLISECONDS.sleep(100);
thread.interrupt();
}

public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.out.println("function of Future.cancel():");
test_cancel(new SleepBlocked());
test_cancel(new JoinBlocked());
test_cancel(new IOBlocked(System.in));
test_cancel(new SynchronizedBlocked());
test_cancel(new RunningThread());

System.out.println("--------------割--------------");
TimeUnit.SECONDS.sleep(3); // 主线程休眠一会,等待前面的线程执行完毕

System.out.println("function of Thread.interrupt():");
test_interrupt(new SleepBlocked());
test_interrupt(new JoinBlocked());
test_interrupt(new IOBlocked(System.in));
test_interrupt(new SynchronizedBlocked());
test_interrupt(new RunningThread());

TimeUnit.SECONDS.sleep(3);
System.out.println("退出");
System.exit(0);
}

}


输出结果:

function of Future.cancel():

SleepBlocked线程休眠中...

SleepBlocked线程休眠期间被中断

JoinBlocked等待子线程执行完毕...

JoinBlocked线程等待子线程执行期间被中断

IOBlocked线程等待输入...

RunningThread线程正常执行中...

--------------割--------------

function of Thread.interrupt():

SleepBlocked线程休眠中...

SleepBlocked线程休眠期间被中断

JoinBlocked等待子线程执行完毕...

JoinBlocked线程等待子线程执行期间被中断

IOBlocked线程等待输入...

SynchronizedBlocked线程等待获取同步锁...

RunningThread线程正常执行中...

退出

发现cancel()方法和interrupt()方法的效果是一样的。

结论: 被sleep()、join()方法阻塞的线程,可以被中断,但是被I/O、同步锁阻塞的线程不能被中断,也不能直接中断正在正常运行的线程。

6、检查中断状态:

1)使用IsInterrupted()

class NormalRunningThread extends Thread { // 一个正常运行的线程
private boolean flag = true;

public void run() {
while (flag)
Thread.yield();
System.out.println("NormalRunningThread线程被打断");
}
}

class BlockedThread extends Thread { // 一个被阻塞的线程

public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("BlockedThread线程被打断");
}
}
}

public class Methods_isInterrupted {
private static Thread thread;

private synchronized static void test_interrupt(Thread t)
throws InterruptedException {
thread = t;
thread.start();

// 线程开启之后,中断状态为false,isInterrupted方法不会影响线程的中断状态
if (thread.isInterrupted())
System.out.println("调用isInterrupted方法后" + thread.getName()
+ "的中断状态为true");

thread.interrupt(); // 设置线程的中断状态为true
if (thread.isInterrupted()) // 判断完线程的中断状态之后,中断状态不变
System.out.println("设置线程的中断状态之后" + thread.getName() + "的中断状态为true");
}

public static void main(String args[]) throws InterruptedException {
test_interrupt(new NormalRunningThread());
test_interrupt(new BlockedThread());

TimeUnit.SECONDS.sleep(2);
System.exit(0);
}
}
输出结果:

设置线程的中断状态之后Thread-0的中断状态为true

设置线程的中断状态之后Thread-1的中断状态为true

BlockedThread线程被打断

发现interrupt()方法的确会将线程的中断状态设置为true,至于线程的中断状态被设置为true之后线程会采取什么操作,那就是线程自己的事了。

2)使用interrupted()

class NeedsCleanup {
private final int id;

public NeedsCleanup(int ident) {
id = ident;
System.out.println("NeedsCleanup " + id);
}

public void cleanup() {
System.out.println("Cleaning up " + id);
}
}

class Blocked implements Runnable {
private volatile double d = 0.0;

@Override
public void run() {
// TODO Auto-generated method stub
try {
while (!Thread.interrupted()) {
NeedsCleanup n1 = new NeedsCleanup(1);
try {
System.out.println("Sleeping");
TimeUnit.SECONDS.sleep(1);
NeedsCleanup n2 = new NeedsCleanup(2);
try {
System.out.println("Calculating"); //干一件复杂的事
for (int i = 0; i < 2500000; i++)
d = d + (Math.PI + Math.E) / d;
System.out.println("Finished time-consuming operation");
} finally {
n2.cleanup();
}
} finally {
n1.cleanup();
}
}
System.out.println("Exiting via while() test");
if(!Thread.currentThread().isInterrupted()) {
System.out.println("中断状态被清除了");
}
} catch (InterruptedException e) {
System.out.println("Exiting via InterruptedException");
}
}

}

public class InterruptingIdiom {

public static void main(String[] args) throws NumberFormatException,
InterruptedException {
// TODO Auto-generated method stub
Thread t = new Thread(new Blocked());
t.start();
TimeUnit.MILLISECONDS.sleep(1100);
t.interrupt();
}

}


说明一下,由于机器性能不同,为了使Blocked线程能在正常工作的时候退出,main线程需要休眠的时间可能不同,这是我的一个测试结果:

NeedsCleanup 1

Sleeping

NeedsCleanup 2

Calculating

Finished time-consuming operation

Cleaning up 2

Cleaning up 1

Exiting via while() test

中断状态被清除了

最后一句话为什么会被打印出来?因为在Blocked线程正常工作期间,调用了interrupt()方法设置线程的中断状态为true,while在进行下一次循环条件(!Thread.interrupted())的检测时,得到的结果为false,但是得到false的同时interrupted()方法会将线程的中断状态清除(也即设置为false)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: