java线程里面的细节问题

在java里面阻塞的函数调用以后会产生什么样的效果呢?java

在生活中, 最多见的阻塞现象是公路上汽车的堵塞. 汽车在公路上快速行驶, 若是前方交通受阻, 就只好停下来等待, 等到交通畅顺, 才能恢复行驶. 
线程在运行中也会由于某些缘由而阻塞. 全部处于阻塞状态的线程的共同特征是: 放弃CPU, 暂停运行, 只有等到致使阻塞的缘由消除, 才能恢复运行; 或者被其余线程中断, 该线程会退出阻塞状态, 而且抛出 InterruptedException.  由于没有CPU因此调用interrupt方法的时候,没法改变你自身的interrupt status,因此,任何产生阻塞的线程,都是放弃当前对CPU的占用。ide

这里上一个demo函数

public class TestInterruptMain {
	public static void main(String[] args) throws InterruptedException {
		TestInterrupt interrupt = new TestInterrupt();
		Thread t1 = new Thread(interrupt);
		t1.start();
		Thread.sleep(10000);
		t1.interrupt();
	}
}


public class TestInterrupt implements Runnable {

	@Override
	public void run() {
		try {
//此时处于阻塞,调用interrupt会抛出异常,由于并无对cpu的占用
			Thread.sleep(1000000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().isInterrupted());
		while (true&&!Thread.currentThread().isInterrupted()) {
			System.out.println(Thread.currentThread().getState());
			System.out.println("Thread is running...");
			long time = System.currentTimeMillis();// 去系统时间的毫秒数
			//不会阻塞
                        while ((System.currentTimeMillis() - time < 1000)) {
			}
		}
	}
	
	
}
相关文章
相关标签/搜索