New method one: implement the Callable interface
●Compared with using Runnable, Callable is more powerful
➢Compared with run() method, it can have return value.
➢ Methods can throw exceptions.
➢Support generic return value.
➢Need to use the FutureTask class, such as getting the returned result.
1. Create a thread by creating NumThread to implement the Callable interface
package com.itzheng.java2;
/*
创建线程的方式三:实现Callable接口。---JDK 5.0新增
*/
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/*
1、创建一个实现Callable的实现类
*/
class NumThread implements Callable{
//2、实现call方法,将此线程需要执行的操作声明在call()方法当中
@Override
public Object call() throws Exception {
int sum = 0;
for (int i = 1; i <= 100 ; i++) {
if(i%2 == 0){
System.out.println(i);
sum += i;
}
}
return sum;
}
}
public class ThreadNew {
public static void main(String[] args) {
// 3、创建Callable接口实现的对象
NumThread numThread = new NumThread();
// 4、将此Callable接口实现的对象作为参数传递到FutureTask构造器当中,创建FutureTask的对象
FutureTask futureTask = new FutureTask(numThread);
//5、将FutureTask的对象作为参数传递到Thread类当中构造器中,创建Thread对象,并调用start()方法
new Thread(futureTask).start();
try {
//6、获取Callable中的call方法的返回值
//get()方法的返回值即为FutureTask构造器参数Callable实现类重写的call()方法的返回值。
Object sum = futureTask.get();
System.out.println("总和为:"+sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
2. How to understand: the way of implementing the Callable interface to create multithreading is more powerful than that of implementing the Runnable interface?
1. Call() can have a return value.
2. Call() can throw an exception, which is captured by outside operations to obtain information about the exception.
3. Callable() supports generics
package com.itzheng.java2;
/*
创建线程的方式三:实现Callable接口。---JDK 5.0新增
如何理解:实现Callable接口的方式创建多线程比实现Runnable接口创建多线程方式强大?
1、call()可以有返回值的
2、call()是可以抛出异常,被外面的操作捕获,获取异常的信息
3、Callable()是支持泛型的
*/
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/*
1、创建一个实现Callable的实现类
*/
class NumThread implements Callable<Integer>{
//2、实现call方法,将此线程需要执行的操作声明在call()方法当中
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i <= 100 ; i++) {
if(i%2 == 0){
System.out.println(i);
sum += i;
}
}
return sum;
}
}
public class ThreadNew {
public static void main(String[] args) {
// 3、创建Callable接口实现的对象
NumThread numThread = new NumThread();
// 4、将此Callable接口实现的对象作为参数传递到FutureTask构造器当中,创建FutureTask的对象
FutureTask<Integer> futureTask = new FutureTask<Integer>(numThread);
//5、将FutureTask的对象作为参数传递到Thread类当中构造器中,创建Thread对象,并调用start()方法
new Thread(futureTask).start();
try {
//6、获取Callable中的call方法的返回值
//get()方法的返回值即为FutureTask构造器参数Callable实现类重写的call()方法的返回值。
Integer sum = futureTask.get();
System.out.println("总和为:"+sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
New method two: use thread pool.
●1. Background:
Frequently created and destroyed resources that are particularly used, such as threads under concurrent conditions,
have a great impact on performance.
● 2. Thinking:
Create multiple threads in advance, put them into the thread pool, get them directly when used, and
put them back into the pool after use . It can avoid frequent creation and destruction and realize reuse. Similar to the public transportation
tools in life .
● 3. Benefits:
➢Improve response speed (reduce the time to create new threads)
➢Reduce resource consumption (reuse threads in the thread pool, no need to create them every time) ➢Easy
thread management
corePoolSize: the size of the core pool
maximumPoolSize: the maximum number of threads
keepAliveTime: threads When there is no task, how long will it last before it will terminate
1. Thread pool related API
1. JDK 5.0 provides thread pool related API: ExecutorService和Executors
2.● ExecutorService
: The real thread pool interface. Common subcategoriesThreadPoolExecutor
➢ void execute(Runnable command):
perform the task / command, no return value - generally used to perform
Runnable
➢ <T> Future<T> submit(Callable<T> task):
perform a task, return values, - as again perform
a Callable
➢ void shutdown():
close the connection pool
3.● Executors
: Tool classes and factory classes for thread pools, used to create and return different types of thread pools
➢ Executors newCachedThreadPool():
Create a thread pool that can create new threads as needed
➢ Executors.newFixedThreadPool(n);
Create a reusable thread pool with a fixed number of threads
➢ Executors.newSingle ThreadExecutor():
Create a thread pool with only one thread
➢ Executors.newScheduledThreadPool(n):
Create a thread pool, which can be scheduled to run commands after a given delay or Perform it regularly.
Second, the corresponding code implementation
package com.itzheng.java2;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
/*
创建线程的方式四:使用线程池
*/
class NumberThread implements Runnable{
@Override
public void run() {
for(int i = 0; i <= 100; i++){
if(i % 2 == 0){
System.out.println(Thread.currentThread().getName() +":"+ i);
}
}
}
}
class NumberThread1 implements Runnable{
@Override
public void run() {
for(int i = 0; i <= 100; i++){
if(i % 2 != 0){
System.out.println(Thread.currentThread().getName() +":"+ i);
}
}
}
}
public class ThreadPool {
public static void main(String[] args) {
//1、提供指定线程数量的连接池
ExecutorService service = Executors.newFixedThreadPool(10);
ThreadPoolExecutor service1 = (ThreadPoolExecutor)service;
//设置线程池的一些属性
System.out.println(service.getClass());//
service1.setCorePoolSize(15);
// service1.setKeepAliveTime();
//2、执行指定的线程的操作。需要提供一个实现Runnable接口或者是 Callable接口实现类的对象
service.execute(new NumberThread());//适合适用于Runnable
service.execute(new NumberThread1());//适合适用于Runnable
//service.submit(new Callable()); 适合使用于Callable
//3、关闭连接池
service.shutdown();
}
}