51--多线程(十)

新增线程创建方式

新增方式一:实现Callable接口
与使用Runnable相比, Callable功能更强大些
1.相比run()方法,可以有返回值
2.方法可以抛出异常
3.支持泛型的返回值
4.需要借助FutureTask类,比如获取返回结果
Future接口
1.可以对具体Runnable、Callable任务的执行结果进行取消、查询是否完成、获取结果等。
2.FutrueTask是Futrue接口的唯一的实现类 
3. FutureTask 同时实现了Runnable, Future接口。它既可以作为 Runnable被线程执行,又可以作为Future得到Callable的返回值

实例:使用两个线程交替打印1~100的数字,并返回最终的和

package com.qwy20;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
//1.创建一个实现Callable的实现类
class MyCallable implements Callable<Integer> {
    
    
	private int num = 1;
	private int sum=0;
	//2.实现call方法,将此线程需要执行的操作声明在call()中
	@Override
	public Integer call() throws Exception {
    
    
		while (true) {
    
    
			synchronized (this) {
    
    
				notify();
				if (num <= 100) {
    
    
					System.out.println(Thread.currentThread().getName() + ",打印:" + num);
					sum+=num;
					num++;
					
				}else{
    
    
					break;
				}	
				wait();
			}
				
			
			
		}
		return sum;

	}

}

public class TestCallable {
    
    
	public static void main(String[] args) {
    
    
		//3.创建Callable接口实现类的对象
		MyCallable my = new MyCallable();
		//4.将此Callable接口实现类的对象作为传递到FutureTask构造器中,创建FutureTask的对象
		FutureTask<Integer> task1 = new FutureTask<>(my);
		FutureTask<Integer> task2 = new FutureTask<>(my);
		//将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start()
		Thread t1 = new Thread(task1);
		Thread t2 = new Thread(task2);
		t1.setName("线程A");
		t2.setName("线程B");
		t1.start();
		t2.start();
		
		try {
    
    
			get()返回值即为FutureTask构造器参数Callable实现类重写的call()的返回值。
			Integer sum = task2.get();
			System.out.println("sum:"+sum);
		} catch (InterruptedException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

运行结果:(省略)
新增方式二:使用线程池
背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程, 对性能影响很大。 思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完 放回池中。可以避 免 频繁创建销毁、实现重复利用。类似生活中的公共交 通工具。
好处:
1.提高响应速度(减少了创建新线程的时间)
2.降低资源消耗(重复利用线程池中线程,不需要每次都创建)
3.便于线程管理
1)corePoolSize:核心池的大小
2)maximumPoolSize:最大线程数
3)keepAliveTime:线程没有任务时最多保持多长时间后会终止  …
线程池相关API
1.JDK 5.0起提供了线程池相关API:ExecutorService 和 Executors 
2.ExecutorService:真正的线程池接口。常见子类ThreadPoolExecutor :
1)void execute(Runnable command) :执行任务/命令,没有返回值,一般用来执行 Runnable 
2) Future submit(Callable task):执行任务,有返回值,一般又来执行 Callable
3)void shutdown() :关闭连接池 
4) Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池
5) Executors.newCachedThreadPool():创建一个可根据需要创建新线程的线程池
6)Executors.newFixedThreadPool(n); 创建一个可重用固定线程数的线程池
7) Executors.newSingleThreadExecutor() :创建一个只有一个线程的线程池
8) Executors.newScheduledThreadPool(n):创建一个线程池,它可安排在给定延迟后运 行命令或者定期地执行。
实例:

public class TestThreadPool {
    
    
	public static void main(String[] args) {
    
    
		//提供一定数量的线程池
		ExecutorService service=Executors.newFixedThreadPool(10);
		
		ThreadPoolExecutor executor=(ThreadPoolExecutor) service;
		/*executor.setCorePoolSize(10);
		executor.setKeepAliveTime(time, unit);*/
		
		MyThread my= new MyThread();
		
		MyThread2 myThread2= new MyThread2();
		executor.execute(my);
		executor.execute(my);
		executor.submit(myThread2);
		executor.submit(myThread2);
		executor.shutdown();
	}
}
class MyThread implements Runnable{
    
    
	private int num=1;
	@Override
	public void run() {
    
    
		while(true){
    
    
			synchronized(this){
    
    
				this.notify();
				if(num<=100){
    
    
					System.out.println(Thread.currentThread().getName()+"打印:"+ num++);
				}else{
    
    
					break;
				}
				try {
    
    
					this.wait();
				} catch (InterruptedException e) {
    
    
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

class MyThread2 implements Callable{
    
    
	private int i=1;
	@Override
	public Object call() throws Exception {
    
    
		
		while(true){
    
    
			synchronized (this) {
    
    
				this.notify();
				if(i<=100){
    
    
					System.out.println(Thread.currentThread().getName()+"打印:"+i);
					i++;
				}else{
    
    
					break;
				}
				this.wait();
			}
		}
		return 0;
	}
	
}

猜你喜欢

转载自blog.csdn.net/qwy715229258163/article/details/114956105