`

Java之 java.util.concurrent 包之ExecutorService之submit () 之 Future

阅读更多
一、如何使用 ExecutorService.submit() ?

submit()
可以接受 Callable 或 Runnable 对象。
返回值是 Future 对象(调用 Future 对象的 get() 方法会导致主线程阻塞)。


二、程序


import java.util.concurrent.Callable;  
import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;  
import java.util.concurrent.TimeUnit;  
import org.junit.Test;

public class TestExecutorService {
	
class Runnabled implements Runnable{  
    @Override  
    public void run() {
        System.out.println("[Runnable-child] running...");  
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }  
    }  
}  
class Callabled implements Callable<String>{  
    @Override  
    public String call() throws Exception {
        System.out.println("[Callable-child] calling...");  
        Thread.sleep(100);
        return "finished";
    }
}
//==========================================================

@Test 
public void test() throws Exception{
	testExecutorService_Runnable();
	testExecutorService_Callable();
	testExecutorService_shutdown();
}

//==========================================================
public void testExecutorService_Runnable() throws Exception {
	
	Runnabled runnable = new Runnabled();  
    ExecutorService es1 = Executors.newCachedThreadPool();
    
    for(int i = 0; i < 10; i++){
        System.out.println("[Runnable] main thread : " + i + "[Blocked in Main]");  
        es1.submit(runnable).get();  
    }
    
    for(int i = 0; i < 10; i++){
        System.out.println("[Runnable] main thread : " + i);              
        es1.execute(runnable);  
      //es1.submit(runnable) // same as, if you don't expect a result.
    }
} 

public void testExecutorService_Callable() throws Exception{
	
	ExecutorService es2 = Executors.newScheduledThreadPool(10);
    Callabled callable = new Callabled();  
    
    for(int i = 0; i < 10; i++){  
        System.out.println("[Callable] main thread : " + i + "[Blocked in Main]");  
        es2.submit(callable).get();  
    }  
   
    for(int i = 0; i < 10; i++){  
        System.out.println("[Callable] main thread : " + i);  
        es2.submit(callable);  
    }
}

public void testExecutorService_shutdown() throws Exception{
	
	ExecutorService es2 = Executors.newScheduledThreadPool(10);
	
	 /* 
	 Does not wait for previously submitted tasks to complete execution.
	 Start an immediately shutdown and no new tasks will be accepted.

	 The invocation has no additional effect if already shut down.
	 */
	es2.shutdown();  
	  
	  
	/* 
	 Blocks, until all tasks have completed execution after  
	 1) a shutdown request,  
	 2) or the timeout occurs,  
	 3) or the current thread is interrupted, 
	 whichever happens first. 
	 */  
	es2.awaitTermination(10000, TimeUnit.SECONDS);  
	  
	System.out.println("----------------------------");  
	System.out.println("print me immediately after all task completed.");  
	System.out.println("no need to wait for 10000 seconds.");  
    
  
}
    
    
   
      
      
/**
NOTE:  ExecutorService.shutdown()         
       VS 
       ExecutorService.awaitTermination() 
 
1. 
awaitTermination() will wait for all task to complete. 
shutdown() method does not wait. 
 
if shutdown() method comes before awaitTermination(), 
Then when all task complete in or less than timeout,  
thread will shut down immediately. 
 
2.  
If you want to get the task result immediately, you should 
use: 
result = exec.submit(Callable/Runnable).get(); 
NOTE: 
If you call get(), it will be blocked. 
If you just call submit(), it will not be blocked. 
 
3. 
If you want to get the task result after all task completed, 
you can store the Future object in to a collection. 
use: 
 
Future f = exec.submit(Callable/Runnable); 
arrayList.add(f); 
 
then after all task completed, you can retrieve the Future 
objects stored in arrayList. 
     
*/  
  
  
/** 
 * NOTE: Callable VS Runnable 
 *  
 * Callable and Runnable are almost same when using 
 * ExecutorService.submit() method. 
 *  
 * They can be both blocked when using Future.get()  
 * method. 
 *  
 * while: 
 * 1. Callable's call() method can return a result. 
 *    Runnable's run()  method is void. 
 *  
 * 2. Callable's call() method throws exception. 
 *    Runnable's run()  method cannot throw exception. 
 */  
  
}  



/*
Result:
===============================================================

[Runnable] main thread : 0 [Blocked in Main]
[Runnable-child] running...
[Runnable] main thread : 1 [Blocked in Main]
[Runnable-child] running...
[Runnable] main thread : 2 [Blocked in Main]
[Runnable-child] running...
[Runnable] main thread : 3 [Blocked in Main]
[Runnable-child] running...
[Runnable] main thread : 4 [Blocked in Main]
[Runnable-child] running...
[Runnable] main thread : 5 [Blocked in Main]
[Runnable-child] running...
[Runnable] main thread : 6 [Blocked in Main]
[Runnable-child] running...
[Runnable] main thread : 7 [Blocked in Main]
[Runnable-child] running...
[Runnable] main thread : 8 [Blocked in Main]
[Runnable-child] running...
[Runnable] main thread : 9 [Blocked in Main]
[Runnable-child] running...

[Runnable] main thread : 0
[Runnable] main thread : 1
[Runnable-child] running...
[Runnable-child] running...
[Runnable] main thread : 2
[Runnable] main thread : 3
[Runnable-child] running...
[Runnable] main thread : 4
[Runnable-child] running...
[Runnable] main thread : 5
[Runnable-child] running...
[Runnable] main thread : 6
[Runnable-child] running...
[Runnable] main thread : 7
[Runnable-child] running...
[Runnable] main thread : 8
[Runnable-child] running...
[Runnable] main thread : 9
[Runnable-child] running...
[Runnable-child] running...


[Callable] main thread :  0 [Blocked in Main]
[Callable-child] calling...
[Callable] main thread :  1 [Blocked in Main]
[Callable-child] calling...
[Callable] main thread :  2 [Blocked in Main]
[Callable-child] calling...
[Callable] main thread :  3 [Blocked in Main]
[Callable-child] calling...
[Callable] main thread :  4 [Blocked in Main]
[Callable-child] calling...
[Callable] main thread :  5 [Blocked in Main]
[Callable-child] calling...
[Callable] main thread :  6 [Blocked in Main]
[Callable-child] calling...
[Callable] main thread :  7 [Blocked in Main]
[Callable-child] calling...
[Callable] main thread :  8 [Blocked in Main]
[Callable-child] calling...
[Callable] main thread :  9 [Blocked in Main]
[Callable-child] calling...

[Callable] main thread : 0
[Callable] main thread : 1
[Callable] main thread : 2
[Callable-child] calling...
[Callable] main thread : 3
[Callable-child] calling...
[Callable-child] calling...
[Callable-child] calling...
[Callable] main thread : 4
[Callable] main thread : 5
[Callable-child] calling...
[Callable-child] calling...
[Callable] main thread : 6
[Callable] main thread : 7
[Callable-child] calling...
[Callable-child] calling...
[Callable] main thread : 8
[Callable] main thread : 9
[Callable-child] calling...
[Callable-child] calling...

----------------------------
print me immediately after all task completed.
no need to wait for 10000 seconds.

 */








java.util.concurrent包之Execuotor系列文章

00_Java之 java.util.concurrent 包之概述

01_Java之java.util.concurrent包之Executor与ExecutorService

02_Java之 java.util.concurrent 包之ExecutorService之submit () 之 Future

03_Java之多线程之Callable与Future

04_Java之多线程之Lock





转载请注明,
原文出处:http://lixh1986.iteye.com/blog/2360306











-
分享到:
评论

相关推荐

    java.util.concurrent.ExecutionException 问题解决方法

    2. **在并发中的应用**:当使用`ExecutorService.submit()`或`Future.get()`方法时,如果后台线程抛出未捕获的异常,这些异常会被包装成`ExecutionException`并抛出给主线程。因此,为了调试并发程序,我们需要检查`...

    java.util.concurrent.uml.pdf

    标题中提到了“java.util.concurrent.uml.pdf”,这表明文件是一份Java并发编程工具包java.util.concurrent的UML(统一建模语言)类结构图的PDF格式文件。UML图能够帮助开发者理解Java并发包中的类、接口及其关系,...

    java concurrent 包 详细解析

    Java并发包(java.concurrent)是Java平台中处理多线程编程的核心工具包,它提供了丰富的类和接口,使得开发者能够高效、安全地编写多线程程序。这个包的设计目标是提高并发性能,减少同步代码的复杂性,并提供高级...

    Java并发任务执行.pdf

    Java `java.util.concurrent`包提供了各种并发工具类,包括`ExecutorService`和`Future`接口,它们允许我们更高效地管理和协调并发任务。例如,可以使用`ExecutorService.newFixedThreadPool(int nThreads)`创建一个...

    java获取压缩文件的名称并解压

    import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class ...

    Java Concurrent处理并发需求

    其中,`java.util.concurrent`包是Java 5引入的一个重要特性,它提供了高级并发机制的支持,使得开发者能够更高效地编写并发程序。 #### 二、Concurrent API的核心组件 `java.util.concurrent`包包含了多个核心...

    java的concurrent用法详解

    `Executor`框架是`java.util.concurrent`的核心组件之一,它为任务的执行提供了一个统一的接口。其中最重要的接口是`ExecutorService`,它定义了线程池的行为,使得我们可以将任务(`Runnable`或`Callable`对象)...

    java 资源搜索并下载(线程等待和通报)

    每个线程负责下载不同的资源,`java.util.concurrent`包提供了丰富的工具,如`ExecutorService`和`Future`,可以方便地管理线程池和控制并发执行。线程池可以避免频繁创建和销毁线程带来的开销。 四、线程等待和...

    米哈游笔试题目-Java方向.docx

    import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class AsyncTaskFramework&lt;T&gt; { private final ExecutorService executor; ...

    java5 thread

    Java5新增了三个多线程相关的包,分别是`java.util.concurrent`、`java.util.concurrent.atomic`和`java.util.concurrent.locks`。这些包提供了大量高级的并发控制工具和数据结构,使得开发者可以更加高效和安全地...

    JAVA中Callable的使用

    Callable接口位于`java.util.concurrent`包下,它的主要方法是`call()`,这个方法相当于Runnable的`run()`,但`call()`可以有返回值和抛出异常。当我们需要在线程中执行一个计算任务并获取结果时,Callable就非常...

    scala futures and promises

    import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class ExecutorServiceCalculator implements Calculator { private int ...

    Java并发编程:设计原则与模式(Concurrent.Programming.in.Java)(中英版)

    例如,使用无锁数据结构或原子操作(`java.util.concurrent.atomic`包)。 3. **避免死锁、活锁和饥饿**:理解并预防这些并发问题至关重要。死锁发生在两个或多个线程相互等待对方释放资源导致僵局;活锁是线程不断...

    Executor,Executors,ExecutorService比较.docx

    `Executors`是`java.util.concurrent`包下的工具类,它提供了多个静态工厂方法,用于创建不同类型的线程池。常见的线程池类型有: - **newFixedThreadPool(int nThreads)**:创建一个固定大小的线程池。线程池的...

    Java多线程之异步Future机制的原理和实现共5页.p

    但请注意,Future对象本身并不执行任何计算,而是与一个对应的`java.util.concurrent.FutureTask`或ExecutorService中的提交任务相关联。 异步Future机制的原理主要体现在以下几个方面: 1. **非阻塞获取结果**:...

    Java并发编程ppt.rar

    4. **Atomic类**:Java并发包`java.util.concurrent.atomic`中的Atomic类提供了一组原子操作,如`AtomicInteger`、`AtomicLong`等,这些类的实例变量更新时具有原子性,可以替代`synchronized`进行简单同步。...

    java多线程并发

    `ExecutorCompletionService`是`java.util.concurrent`包提供的一个类,它结合了`ExecutorService`和`BlockingQueue`的功能,用于管理和获取已完成的任务结果。 综上所述,Java中的多线程并发机制非常强大,不仅...

    Java线程超时监控

    首先,我们可以使用`java.util.concurrent`包中的`Future`和`ExecutorService`来实现线程超时。`ExecutorService`是一个接口,它提供了管理和控制线程池的能力,而`Future`则表示异步计算的结果。当我们提交一个任务...

    java_card3.zip

    首先,线程池是Java并发编程中的重要概念,它是由`java.util.concurrent`包下的`ExecutorService`接口及其实现类如`ThreadPoolExecutor`构成的。线程池可以有效地管理多个线程,避免了频繁创建和销毁线程带来的开销...

    Java高并发程序设计_java_

    2. **并发控制**:Java提供了多种并发控制机制,如`synchronized`关键字用于实现互斥访问,`volatile`关键字确保变量的可见性和有序性,以及`java.util.concurrent`包下的`Lock`接口和`ReentrantLock`类,提供更细...

Global site tag (gtag.js) - Google Analytics