面试求职中需要了解的Java多线程知识(二)

2014-11-23 22:38:34 · 作者: · 浏览: 7
public static void main(String[] args) {
//使用动态缓存线程池,池中的线程随着任务数量的变化而变化
ExecutorService threadPool = Executors.newCachedThreadPool();
//循环产生5个任务丢给线程池
for(int i=1; i<=5; i++){
final int taskNum = i;
threadPool.execute(new Runnable() {
@Override
public void run() {
for(int j=1; j<=2; j++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("任务[" + taskNum + "]使用线程[" + Thread.currentThread().getName() + "]循环打印数据:" + j);
}
}
});//end execute(..);
}//end for(var i)
//如果线程中任务执行完毕,没有任务需要执行了,就关闭线程池,如果不关闭,程序就不会结束,而是持续等待新的任务.
threadPool.shutdown();
}
}
传统的实现方式以及上面的线程实现方式都不可能有返回值.在ExecutorService中定义了系列的submit(xxx)方法,该方法可以返回Future接口,通过调用其V get() throws InterruptedException, ExecutionException;就可以获取到线程执行结果.submit可以传滴一个Runnable接口的实现类,也可以传递一个Callable接口的实现类.
Callable接口的实现类[JDK源码引入]
public interface Callable {
V call() throws Exception;
}
说明:Future代表一个异步执行的操作,通过get()方法可以获得操作的结果,如果异步操作还没有完成,则get()会使当前线程阻塞,直到计算完成.
编写5.0新线程的步骤
1.先写一个Callable的子类,然后实现call()方法.
2.调用Executors.newXXThreadPool()返回ExecutorService类型.
3.调用ExecutorService中的submit(Callable的子类)方法启动线程.
4.只有调用ExecutorService的shutdown()方法才能真正的离开 虚拟机.
import java.util.concurrent.*;
public class ExecutorTest implements Callable {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
//创建缓存线程池
ExecutorService pool = Executors.newCachedThreadPool();
//指定线程,获取线程返回结果
Future returnV = pool.submit(new ExecutorTest());
//获取线程返回结果
System.out.println("" + returnV.get().toString());
//关闭线程池
pool.shutdown();
}
@Override
public Object call() throws Exception {
for(int i=1; i<=5; i++){
Thread.sleep (500);
System.out .println(Thread.currentThread().getName()+" print value " +i);
}
return "Multiple Thread Implements Callable";
}
}