The code copy is as follows:
package com.yao;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* New task execution architecture.
* Before Java 5.0, a task was started by calling the start() method of the Thread class.
* The task submission and execution are carried out simultaneously. If you want to schedule the task execution,
* Or controlling the number of threads executed simultaneously requires additional code to complete.
* 5.0 provides a new task execution architecture that allows you to easily schedule and control the execution of tasks.
* And a thread pool similar to a database connection pool can be established to perform tasks.
* This architecture mainly consists of three interfaces and their corresponding specific classes.
*These three interfaces are Executor, ExecutorService and ScheduledExecutorService.
* (1) Executor interface: is used to execute Runnable tasks, it only defines one method:
* execute(Runnable command): execute Ruannable type tasks
* (2) ExecutorService: inherits the Executor method and provides services to execute Callable tasks and abort task execution.
* The main methods of its definition are:
* submit(task): Can be used to submit Callable or Runnable tasks and return the Future object representing this task
* invokeAll(collection of tasks): Batch collection of tasks and return a collection of Future objects representing these tasks.
* shutdown(): Close the service after completing the submitted task and no longer accepts new tasks.
* shutdownNow(): Stops all executing tasks and closes the service.
* isTerminated(): Test whether all tasks have been executed.
* isShutdown(): Test whether the ExecutorService has been closed
* (3) ScheduledExecutorService: Inherits ExecutorService, providing the function of scheduling tasks according to time,
* schedule(task, initDelay): Schedule the submitted Callable or Runnable task to be executed after the time specified by initDelay.
* scheduleAtFixedRate(): Schedule the submitted Runnable task to be executed repeatedly at the specified interval.
* scheduleWithFixedDelay(): Schedule the submitted Runnable task to be executed repeatedly after each execution, wait for the time specified by delay.
*
* Obtain various service objects through the Executors class.
* callable(Runnable task): convert Runnable tasks into Callable tasks
* newSingleThreadExecutor: Generates an ExecutorService object, which has only one thread that can be used to execute tasks. If there are more than one task, the tasks will be executed in sequence.
* newCachedThreadPool(): Generates an ExecutorService object, which has a thread pool. The size of the thread pool will be adjusted as needed. After the thread executes the task, it returns to the thread pool for the next task to be used.
* newFixedThreadPool(int poolSize): Generates an ExecutorService object, which has a thread pool of size poolSize. If the number of tasks is greater than poolSize, the tasks will be executed in a queue in sequence.
* newSingleThreadScheduledExecutor: Generates a ScheduledExecutorService object, the thread pool size of this object is 1. If there are more than one task, the tasks will be executed in sequence.
* newScheduledThreadPool(int poolSize): Generates a ScheduledExecutorService object, the thread pool size of this object is poolSize. If the number of tasks is greater than poolSize, the task will wait for execution in a queue
*/
public class ExecuteArch {
/**
* This thread outputs a string
*/
public static class MyThread implements Runnable {
public void run() {
System.out.println("Task repeating. " + System.currentTimeMillis());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Task interrupted. "
+ System.currentTimeMillis());
}
}
}
/**
* The Callable ends another task
*/
public static class MyCallable implements Callable {
private Future future;
public MyCallable(Future future) {
this.future = future;
}
public String call() {
System.out.println("To cancel Task..."
+ +System.currentTimeMillis());
this.future.cancel(true);
return "Task cancelled!";
}
}
/**
* @param args
* @throws ExecutionException
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException,
ExecutionException {
// Generate an ExecutorService object, which has a thread pool, and the size of the thread pool will be adjusted as needed.
// After the thread executes the task, it returns to the thread pool for the next task to be used.
ExecutorService cachedService = Executors.newCachedThreadPool();
Future myThreadFuture = cachedService.submit(new MyThread());
Future myCallableFuture = cachedService.submit(new MyCallable(
myThreadFuture));
System.out.println(myCallableFuture.get());
System.out.println("-----------------");
// Convert Runnable tasks to Callable tasks
Callable myThreadCallable = Executors.callable(new MyThread());
Future myThreadCallableFuture = cachedService.submit(myThreadCallable);
// For Runnable tasks, no value is returned after being converted to Callable tasks
System.out.println(myThreadCallableFuture.get());
cachedService.shutdownNow();
System.out.println("-----------------");
// Generate an ExecutorService object, which has a thread pool of size poolSize.
// If the number of tasks is greater than poolSize, the tasks will be executed in a queue in sequence
ExecutorService fixedService = Executors.newFixedThreadPool(2);
fixedService.submit(new MyThread());
fixedService.submit(new MyThread());
// Since the thread pool size is 2, the subsequent tasks must wait for the previous tasks to be executed before they can be executed.
myThreadFuture = fixedService.submit(new MyThread());
myCallableFuture = fixedService.submit(new MyCallable(myThreadFuture));
System.out.println(myCallableFuture.get());
fixedService.shutdownNow();
System.out.println("-----------------");
// Generate a ScheduledExecutorService object, the thread pool size of this object is poolSize.
// If the number of tasks is greater than poolSize, the task will wait for execution in a queue
ScheduledExecutorService fixedScheduledService = Executors
.newScheduledThreadPool(2);
// Create new task 1
MyThread task1 = new MyThread();
// Use the Task Execution Service to execute task 1 immediately, and then execute task 1 every 2 seconds thereafter.
myThreadFuture = fixedScheduledService.scheduleAtFixedRate(task1, 0, 2,
TimeUnit.SECONDS);
// Create new task 2
MyCallable task2 = new MyCallable(myThreadFuture);
// Use the task execution service to wait for 5 seconds before executing task 2. After executing it, task 1 will be closed.
myCallableFuture = fixedScheduledService.schedule(task2, 5,
TimeUnit.SECONDS);
System.out.println(myCallableFuture.get());
fixedScheduledService.shutdownNow();
}
}