ITeye博客

thread interrupt

wjg_java · 2016-03-21 14:31 · thread · 编程语言 · Markdown

Thread thread4 = new Thread(){ public void run(){ try { //synchronized(this){ //this.wait(10000); System.out.println("start A4"); System.out.println("A4 interrupt "+currentThread().isInterrupted()); currentThread().sleep(100000); long time= System.currentTimeMillis(); while(System.currentTimeMillis()-time<20000) {

					}
					System.out.println("end  A4");
					//}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				System.out.println("B4");
				System.out.println("B4 interrupt  "+currentThread().isInterrupted());
			}
		}
		
	};
	 
	thread4.start();

//主线程休眠 start try { Thread.sleep(5000l); } catch (InterruptedException e) { // TODO Auto-generated catch block System.out.println("B5"); } ////主线程休眠 end System.out.println("interrupt...start"); thread4.interrupt();

	System.out.println("interrupt...end");

如上代码,interrupt的作用就是设置打断状态true或者false; 如果调用过thread4.interrupt(); 则再调用sleep join wait就会抛出InterruptedException异常,并且再次把interrupt状态设置为false;如果没有调用sleep join wait,那么我们可以发现在thread4.interrupt()之后currentThread().isInterrupted()为true。

第二种情况 当被block之后,我发现也会抛出InterruptedException,代码如下 Thread thread4 = new Thread(){ public void run(){ try { //synchronized(this){ //this.wait(10000); System.out.println("start A4"); System.out.println("A4 interrupt "+currentThread().isInterrupted()); BlockingQueue q= new ArrayBlockingQueue(2); q.put("d"); q.put("d"); q.put("d"); System.out.println("end A4"); //} } catch (Exception e) { // TODO Auto-generated catch block System.out.println("B4"); System.out.println("B4 interrupt "+currentThread().isInterrupted()); } }

	};
	 
	thread4.start();

// try { // Thread.sleep(5000l); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // System.out.println("B5"); // } System.out.println("interrupt...start"); thread4.interrupt();

	System.out.println("interrupt...end");

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。