java_thread interrupt 理解_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java_thread interrupt 理解

java_thread interrupt 理解

 2014/4/25 16:18:39  it_like  程序员俱乐部  我要评论(0)
  • 摘要:packagecom.java.util.concurrent;importjava.util.concurrent.Callable;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.concurrent.Future;publicclassTest1{publicstaticvoidmain(String[]args)throwsException
  • 标签:thread Java 理解

?

class="中断举例 ">package com.java.util.concurrent;


import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Test1 {
	
	public static void main(String[] args) throws Exception {
		
		ExecutorService exeService = Executors.newFixedThreadPool(1);
		
		Future<Thread> future = exeService.submit(new CallableC<CallObj>(new CallObj()));
		// exeService.submit(new CallableC<CallObj>(new CallObj()));  blocking quene
		Thread s = future.get();// get() is blocking 
		System.out.println(s);
		System.out.println(s.isInterrupted());
		
	}
	
	static class CallObj{
		@Override
		public String toString() {
			
			return System.currentTimeMillis()+"";
		}
	}
	

	static class CallableC<V> implements Callable{
		

		private V obj ;
		public CallableC(V o) {
			obj = o;
		}
		
		@Override
		public Thread call() throws Exception {
			System.out.println("start.....");
			int i = 0;
			try {
				while (true) {
					call(obj);
					Thread.sleep(1000);// in sleep(),weather interrupted;     i=7,currentThread is interrupted 
					i++;
					if(i>5)// 7 times ; i=6 currentThread.interrupt()
						Thread.currentThread().interrupt();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				System.out.println("done.....");
			}

			return Thread.currentThread();
		}
		
		
		public String call(V arg){
			System.out.println(Thread.currentThread().getName());
			return null;
		}
		
	}
	
}

中断特点:

?? 1. 只能中断线程阻塞 时

?? 2. 中断不影响thread代码逻辑,只是一个标志位的改变和中断异常的表示

?

?

??? Thread.currentThread().interrupt(); 会把Thread,中断标志位 标志为 true,

??? Thread.sleep() ; 方法内部Thread会判断当前线程的中断标志位,为true,则抛出中断异常

??? Thread被中断(这里(上面的代码)是指抛出中断异常了),thread仍继续执行,如果没有使用中断标志位进行其它的逻辑处理,中断就没有意义

??

?

?

?

?

?

?

?

发表评论
用户名: 匿名